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