home *** CD-ROM | disk | FTP | other *** search
/ Liren Large Software Subsidy 7 / 07.iso / c / c019 / 3.ddi / PZXXX / LZARI.C < prev    next >
Encoding:
C/C++ Source or Header  |  1989-04-11  |  12.6 KB  |  463 lines

  1. /**************************************************************
  2.     LZARI.C -- A Data Compression Program
  3.     (tab = 4 spaces)
  4. ***************************************************************
  5.     4/7/1989 Haruhiko Okumura
  6.     Use, distribute, and modify this program freely.
  7.     Please send me your improved versions.
  8.         PC-VAN        SCIENCE
  9.         NIFTY-Serve    PAF01022
  10.         CompuServe    74050,1022
  11. **************************************************************/
  12. #include <stdio.h>
  13. #include <stdlib.h>
  14. #include <string.h>
  15. #include <ctype.h>
  16.  
  17. #define    EXIT_FAILURE    -1    /* sgg */
  18. #define    EXIT_SUCCESS    0    /* sgg */
  19.  
  20.  
  21. /********** Bit I/O **********/
  22.  
  23. FILE  *infile, *outfile;
  24. unsigned long int  textsize = 0, codesize = 0, printcount = 0;
  25.  
  26. void Error(char *message)
  27. {
  28.     printf("\n%s\n", message);
  29.     exit(EXIT_FAILURE);
  30. }
  31.  
  32. void PutBit(int bit)  /* Output one bit (bit = 0,1) */
  33. {
  34.     static unsigned int  buffer = 0, mask = 128;
  35.     
  36.     if (bit) buffer |= mask;
  37.     if ((mask >>= 1) == 0) {
  38.         if (putc(buffer, outfile) == EOF) Error("Write Error");
  39.         buffer = 0;  mask = 128;  codesize++;
  40.     }
  41. }
  42.  
  43. void FlushBitBuffer(void)  /* Send remaining bits */
  44. {
  45.     int  i;
  46.     
  47.     for (i = 0; i < 7; i++) PutBit(0);
  48. }
  49.  
  50. int GetBit(void)  /* Get one bit (0 or 1) */
  51. {
  52.     static unsigned int  buffer, mask = 0;
  53.     
  54.     if ((mask >>= 1) == 0) {
  55.         buffer = getc(infile);  mask = 128;
  56.     }
  57.     return ((buffer & mask) != 0);
  58. }
  59.  
  60. /********** LZSS with multiple binary trees **********/
  61.  
  62. #define N         4096    /* size of ring buffer */
  63. #define F           60    /* upper limit for match_length */
  64. #define THRESHOLD    2   /* encode string into position and length
  65.                            if match_length is greater than this */
  66. #define NIL            N    /* index for root of binary search trees */
  67.  
  68. unsigned char  text_buf[N + F - 1];    /* ring buffer of size N,
  69.             with extra F-1 bytes to facilitate string comparison */
  70. int        match_position, match_length,  /* of longest match.  These are
  71.             set by the InsertNode() procedure. */
  72.         lson[N + 1], rson[N + 257], dad[N + 1];  /* left & right children &
  73.             parents -- These constitute binary search trees. */
  74.  
  75. void InitTree(void)  /* Initialize trees */
  76. {
  77.     int  i;
  78.  
  79.     /* For i = 0 to N - 1, rson[i] and lson[i] will be the right and
  80.        left children of node i.  These nodes need not be initialized.
  81.        Also, dad[i] is the parent of node i.  These are initialized to
  82.        NIL (= N), which stands for 'not used.'
  83.        For i = 0 to 255, rson[N + i + 1] is the root of the tree
  84.        for strings that begin with character i.  These are initialized
  85.        to NIL.  Note there are 256 trees. */
  86.  
  87.     for (i = N + 1; i <= N + 256; i++) rson[i] = NIL;    /* root */
  88.     for (i = 0; i < N; i++) dad[i] = NIL;    /* node */
  89. }
  90.  
  91. void InsertNode(int r)
  92.     /* Inserts string of length F, text_buf[r..r+F-1], into one of the
  93.        trees (text_buf[r]'th tree) and returns the longest-match position
  94.        and length via the global variables match_position and match_length.
  95.        If match_length = F, then removes the old node in favor of the new
  96.        one, because the old one will be deleted sooner.
  97.        Note r plays double role, as tree node and position in buffer. */
  98. {
  99.     int  i, p, cmp, temp;
  100.     unsigned char  *key;
  101.  
  102.     cmp = 1;  key = &text_buf[r];  p = N + 1 + key[0];
  103.     rson[r] = lson[r] = NIL;  match_length = 0;
  104.     for ( ; ; ) {
  105.         if (cmp >= 0) {
  106.             if (rson[p] != NIL) p = rson[p];
  107.             else {  rson[p] = r;  dad[r] = p;  return;  }
  108.         } else {
  109.             if (lson[p] != NIL) p = lson[p];
  110.             else {  lson[p] = r;  dad[r] = p;  return;  }
  111.         }
  112.         for (i = 1; i < F; i++)
  113.             if ((cmp = key[i] - text_buf[p + i]) != 0)  break;
  114.         if (i > THRESHOLD) {
  115.             if (i > match_length) {
  116.                 match_position = (r - p) & (N - 1);
  117.                 if ((match_length = i) >= F) break;
  118.             } else if (i == match_length) {
  119.                 if ((temp = (r - p) & (N - 1)) < match_position)
  120.                     match_position = temp;
  121.             }
  122.         }
  123.     }
  124.     dad[r] = dad[p];  lson[r] = lson[p];  rson[r] = rson[p];
  125.     dad[lson[p]] = r;  dad[rson[p]] = r;
  126.     if (rson[dad[p]] == p) rson[dad[p]] = r;
  127.     else                   lson[dad[p]] = r;
  128.     dad[p] = NIL;  /* remove p */
  129. }
  130.  
  131. void DeleteNode(int p)  /* Delete node p from tree */
  132. {
  133.     int  q;
  134.     
  135.     if (dad[p] == NIL) return;  /* not in tree */
  136.     if (rson[p] == NIL) q = lson[p];
  137.     else if (lson[p] == NIL) q = rson[p];
  138.     else {
  139.         q = lson[p];
  140.         if (rson[q] != NIL) {
  141.             do {  q = rson[q];  } while (rson[q] != NIL);
  142.             rson[dad[q]] = lson[q];  dad[lson[q]] = dad[q];
  143.             lson[q] = lson[p];  dad[lson[p]] = q;
  144.         }
  145.         rson[q] = rson[p];  dad[rson[p]] = q;
  146.     }
  147.     dad[q] = dad[p];
  148.     if (rson[dad[p]] == p) rson[dad[p]] = q;
  149.     else                   lson[dad[p]] = q;
  150.     dad[p] = NIL;
  151. }
  152.  
  153. /********** Arithmetic Compression **********/
  154.  
  155. /*  If you are not familiar with arithmetic compression, you should read
  156.         I. E. Witten, R. M. Neal, and J. G. Cleary,
  157.             Communications of the ACM, Vol. 30, pp. 520-540 (1987),
  158.     from which much have been borrowed.  */
  159.  
  160. #define M   15
  161.  
  162. /*    Q1 (= 2 to the M) must be sufficiently large, but not so
  163.     large as the unsigned long 4 * Q1 * (Q1 - 1) overflows.  */
  164.  
  165. #define Q1  (1UL << M)
  166. #define Q2  (2 * Q1)
  167. #define Q3  (3 * Q1)
  168. #define Q4  (4 * Q1)
  169. #define MAX_CUM (Q1 - 1)
  170.  
  171. #define N_CHAR  (256 - THRESHOLD + F)
  172.     /* character code = 0, 1, ..., N_CHAR - 1 */
  173.  
  174. unsigned long int  low = 0, high = Q4, value = 0;
  175. int  shifts = 0;  /* counts for magnifying low and high around Q2 */
  176. int  char_to_sym[N_CHAR], sym_to_char[N_CHAR + 1];
  177. unsigned int
  178.     sym_freq[N_CHAR + 1],  /* frequency for symbols */
  179.     sym_cum[N_CHAR + 1],   /* cumulative freq for symbols */
  180.     position_cum[N + 1];   /* cumulative freq for positions */
  181.  
  182. void StartModel(void)  /* Initialize model */
  183. {
  184.     int ch, sym, i;
  185.     
  186.     sym_cum[N_CHAR] = 0;
  187.     for (sym = N_CHAR; sym >= 1; sym--) {
  188.         ch = sym - 1;
  189.         char_to_sym[ch] = sym;  sym_to_char[sym] = ch;
  190.         sym_freq[sym] = 1;
  191.         sym_cum[sym - 1] = sym_cum[sym] + sym_freq[sym];
  192.     }
  193.     sym_freq[0] = 0;  /* sentinel (!= sym_freq[1]) */
  194.     position_cum[N] = 0;
  195.     for (i = N; i >= 1; i--)
  196.         position_cum[i - 1] = position_cum[i] + 10000 / (i + 200);
  197.             /* empirical distribution function (quite tentative) */
  198.             /* Please devise a better mechanism! */
  199. }
  200.  
  201. void UpdateModel(int sym)
  202. {
  203.     int i, c, ch_i, ch_sym;
  204.     
  205.     if (sym_cum[0] >= MAX_CUM) {
  206.         c = 0;
  207.         for (i = N_CHAR; i > 0; i--) {
  208.             sym_cum[i] = c;
  209.             c += (sym_freq[i] = (sym_freq[i] + 1) >> 1);
  210.         }
  211.         sym_cum[0] = c;
  212.     }
  213.     for (i = sym; sym_freq[i] == sym_freq[i - 1]; i--) ;
  214.     if (i < sym) {
  215.         ch_i = sym_to_char[i];    ch_sym = sym_to_char[sym];
  216.         sym_to_char[i] = ch_sym;  sym_to_char[sym] = ch_i;
  217.         char_to_sym[ch_i] = sym;  char_to_sym[ch_sym] = i;
  218.     }
  219.     sym_freq[i]++;
  220.     while (--i >= 0) sym_cum[i]++;
  221. }
  222.  
  223. static void Output(int bit)  /* Output 1 bit, followed by its complements */
  224. {
  225.     PutBit(bit);
  226.     for ( ; shifts > 0; shifts--) PutBit(! bit);
  227. }
  228.  
  229. void EncodeChar(int ch)
  230. {
  231.     int  sym;
  232.     unsigned long int  range;
  233.  
  234.     sym = char_to_sym[ch];
  235.     range = high - low;
  236.     high = low + (range * sym_cum[sym - 1]) / sym_cum[0];
  237.     low +=       (range * sym_cum[sym    ]) / sym_cum[0];
  238.     for ( ; ; ) {
  239.         if (high <= Q2) Output(0);
  240.         else if (low >= Q2) {
  241.             Output(1);  low -= Q2;  high -= Q2;
  242.         } else if (low >= Q1 && high <= Q3) {
  243.             shifts++;  low -= Q1;  high -= Q1;
  244.         } else break;
  245.         low += low;  high += high;
  246.     }
  247.     UpdateModel(sym);
  248. }
  249.  
  250. void EncodePosition(int position)
  251. {
  252.     unsigned long int  range;
  253.  
  254.     range = high - low;
  255.     high = low + (range * position_cum[position    ]) / position_cum[0];
  256.     low +=       (range * position_cum[position + 1]) / position_cum[0];
  257.     for ( ; ; ) {
  258.         if (high <= Q2) Output(0);
  259.         else if (low >= Q2) {
  260.             Output(1);  low -= Q2;  high -= Q2;
  261.         } else if (low >= Q1 && high <= Q3) {
  262.             shifts++;  low -= Q1;  high -= Q1;
  263.         } else break;
  264.         low += low;  high += high;
  265.     }
  266. }
  267.  
  268. void EncodeEnd(void)
  269. {
  270.     shifts++;
  271.     if (low < Q1) Output(0);  else Output(1);
  272.     FlushBitBuffer();  /* flush bits remaining in buffer */
  273. }
  274.  
  275. int BinarySearchSym(unsigned int x)
  276.     /* 1      if x >= sym_cum[1],
  277.        N_CHAR if sym_cum[N_CHAR] > x,
  278.        i such that sym_cum[i - 1] > x >= sym_cum[i] otherwise */
  279. {
  280.     int i, j, k;
  281.     
  282.     i = 1;  j = N_CHAR;
  283.     while (i < j) {
  284.         k = (i + j) / 2;
  285.         if (sym_cum[k] > x) i = k + 1;  else j = k;
  286.     }
  287.     return i;
  288. }
  289.  
  290. int BinarySearchPos(unsigned int x)
  291.     /* 0 if x >= position_cum[1],
  292.        N - 1 if position_cum[N] > x,
  293.        i such that position_cum[i] > x >= position_cum[i + 1] otherwise */
  294. {
  295.     int i, j, k;
  296.     
  297.     i = 1;  j = N;
  298.     while (i < j) {
  299.         k = (i + j) / 2;
  300.         if (position_cum[k] > x) i = k + 1;  else j = k;
  301.     }
  302.     return i - 1;
  303. }
  304.  
  305. void StartDecode(void)
  306. {
  307.     int i;
  308.  
  309.     for (i = 0; i < M + 2; i++)
  310.         value = 2 * value + GetBit();
  311. }
  312.  
  313. int DecodeChar(void)
  314. {
  315.     int     sym, ch;
  316.     unsigned long int  range;
  317.     
  318.     range = high - low;
  319.     sym = BinarySearchSym((unsigned int)
  320.         (((value - low + 1) * sym_cum[0] - 1) / range));
  321.     high = low + (range * sym_cum[sym - 1]) / sym_cum[0];
  322.     low +=       (range * sym_cum[sym    ]) / sym_cum[0];
  323.     for ( ; ; ) {
  324.         if (low >= Q2) {
  325.             value -= Q2;  low -= Q2;  high -= Q2;
  326.         } else if (low >= Q1 && high <= Q3) {
  327.             value -= Q1;  low -= Q1;  high -= Q1;
  328.         } else if (high > Q2) break;
  329.         low += low;  high += high;
  330.         value = 2 * value + GetBit();
  331.     }
  332.     ch = sym_to_char[sym];
  333.     UpdateModel(sym);
  334.     return ch;
  335. }
  336.  
  337. int DecodePosition(void)
  338. {
  339.     int position;
  340.     unsigned long int  range;
  341.     
  342.     range = high - low;
  343.     position = BinarySearchPos((unsigned int)
  344.         (((value - low + 1) * position_cum[0] - 1) / range));
  345.     high = low + (range * position_cum[position    ]) / position_cum[0];
  346.     low +=       (range * position_cum[position + 1]) / position_cum[0];
  347.     for ( ; ; ) {
  348.         if (low >= Q2) {
  349.             value -= Q2;  low -= Q2;  high -= Q2;
  350.         } else if (low >= Q1 && high <= Q3) {
  351.             value -= Q1;  low -= Q1;  high -= Q1;
  352.         } else if (high > Q2) break;
  353.         low += low;  high += high;
  354.         value = 2 * value + GetBit();
  355.     }
  356.     return position;
  357. }
  358.  
  359. /********** Encode and Decode **********/
  360.  
  361. void Encode(void)
  362. {
  363.     int  i, c, len, r, s, last_match_length;
  364.     
  365.     fseek(infile, 0L, SEEK_END);
  366.     textsize = ftell(infile);
  367.     if (fwrite(&textsize, sizeof textsize, 1, outfile) < 1)
  368.         Error("Write Error");  /* output size of text */
  369.     codesize += sizeof textsize;
  370.     if (textsize == 0) return;
  371.     rewind(infile);  textsize = 0;
  372.     StartModel();  InitTree();
  373.     s = 0;  r = N - F;
  374.     for (i = s; i < r; i++) text_buf[i] = ' ';
  375.     for (len = 0; len < F && (c = getc(infile)) != EOF; len++)
  376.         text_buf[r + len] = c;
  377.     textsize = len;
  378.     for (i = 1; i <= F; i++) InsertNode(r - i);
  379.     InsertNode(r);
  380.     do {
  381.         if (match_length > len) match_length = len;
  382.         if (match_length <= THRESHOLD) {
  383.             match_length = 1;  EncodeChar(text_buf[r]);
  384.         } else {
  385.             EncodeChar(255 - THRESHOLD + match_length);
  386.             EncodePosition(match_position - 1);
  387.         }
  388.         last_match_length = match_length;
  389.         for (i = 0; i < last_match_length &&
  390.                 (c = getc(infile)) != EOF; i++) {
  391.             DeleteNode(s);  text_buf[s] = c;
  392.             if (s < F - 1) text_buf[s + N] = c;
  393.             s = (s + 1) & (N - 1);
  394.             r = (r + 1) & (N - 1);
  395.             InsertNode(r);
  396.         }
  397.         if ((textsize += i) > printcount) {
  398.             printf("%12ld\r", textsize);  printcount += 1024;
  399.         }
  400.         while (i++ < last_match_length) {
  401.             DeleteNode(s);
  402.             s = (s + 1) & (N - 1);
  403.             r = (r + 1) & (N - 1);
  404.             if (--len) InsertNode(r);
  405.         }
  406.     } while (len > 0);
  407.     EncodeEnd();
  408.     printf("In : %lu bytes\n", textsize);
  409.     printf("Out: %lu bytes\n", codesize);
  410.     printf("Out/In: %.3f\n", (double)codesize / textsize);
  411. }
  412.  
  413. void Decode(void)
  414. {
  415.     int  i, j, k, r, c;
  416.     unsigned long int  count;
  417.  
  418.     if (fread(&textsize, sizeof textsize, 1, infile) < 1)
  419.         Error("Read Error");  /* read size of text */
  420.     if (textsize == 0) return;
  421.     StartDecode();  StartModel();
  422.     for (i = 0; i < N - F; i++) text_buf[i] = ' ';
  423.     r = N - F;
  424.     for (count = 0; count < textsize; ) {
  425.         c = DecodeChar();
  426.         if (c < 256) {
  427.             putc(c, outfile);  text_buf[r++] = c;
  428.             r &= (N - 1);  count++;
  429.         } else {
  430.             i = (r - DecodePosition() - 1) & (N - 1);
  431.             j = c - 255 + THRESHOLD;
  432.             for (k = 0; k < j; k++) {
  433.                 c = text_buf[(i + k) & (N - 1)];
  434.                 putc(c, outfile);  text_buf[r++] = c;
  435.                 r &= (N - 1);  count++;
  436.             }
  437.         }
  438.         if (count > printcount) {
  439.             printf("%12lu\r", count);  printcount += 1024;
  440.         }
  441.     }
  442.     printf("%12lu\n", count);
  443. }
  444.  
  445. int main(int argc, char *argv[])
  446. {
  447.     char  *s;
  448.     
  449.     if (argc != 4) {
  450.         printf("'lzari e file1 file2' encodes file1 into file2.\n"
  451.                "'lzari d file2 file1' decodes file2 into file1.\n");
  452.         return EXIT_FAILURE;
  453.     }
  454.     if ((s = argv[1], s[1] || strpbrk(s, "DEde") == NULL)
  455.      || (s = argv[2], (infile  = fopen(s, "rb")) == NULL)
  456.      || (s = argv[3], (outfile = fopen(s, "wb")) == NULL)) {
  457.         printf("??? %s\n", s);  return EXIT_FAILURE;
  458.     }
  459.     if (toupper(*argv[1]) == 'E') Encode();  else Decode();
  460.     fclose(infile);  fclose(outfile);
  461.     return EXIT_SUCCESS;
  462. }
  463.