home *** CD-ROM | disk | FTP | other *** search
/ QBasic & Borland Pascal & C / Delphi5.iso / C / Samples / COMPRESS.ARJ / LZ / LZARI.C < prev    next >
Encoding:
C/C++ Source or Header  |  1989-07-12  |  12.6 KB  |  461 lines

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