summaryrefslogtreecommitdiff
path: root/Build/source/libs/potrace/potrace-1.11/src/lzw.c
blob: 236a011abbead281a193b14b953333d1f285ec9c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
/* Copyright (C) 2001-2013 Peter Selinger.
   This file is part of Potrace. It is free software and it is covered
   by the GNU General Public License. See the file COPYING for details. */


/* code for adaptive LZW compression, as used in PostScript. */

#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>

#include "lists.h"
#include "bitops.h"
#include "lzw.h"

/* ---------------------------------------------------------------------- */
/* compression state specification */

/* The compression algorithm follows the following specification,
   expressed as a state machine. A state is a triple {s,d,n}, where s
   is a string of input symbols, d is a dictionary, which is a
   function from strings to output symbols, and n is the dictionary
   size, or equivalently, the next unused output symbol. There are
   also special states init and stop. emit[b, code] is a function
   which emits the code 'code' as a b-bit value into the output
   bitstream. hibit(n) returns the least number of binary digits
   required to represent n.

   init ---> {[], newdict, 258}

     where [] is the empty string, and newdict maps each of the 256
     singleton strings to itself. (Note that there are two special
     output symbols 256 and 257, so that the next available one is
     258). Note: hibit(258)=9.

   {[], d, n} (input c) ---> (emit[hibit(n), 256]) {c, d, n}

   {s,d,n} (input c) ---> {s*c,d,n}

     if s!=[], s*c is in the domain of d. Here s*c is the strings s
     extended by the character c.

   {s,d,n} (input c) ---> (emit[hibit(n), d(s)]) {c,d',n+1}

     if s!=[], s*c is not in the domain of d, and hibit(n+2) <= 12.
     Here d'=d+{s*c->n}.

   {s,d,n} (input c) ---> 
           (emit[hibit(n), d(s)]) (emit[hibit(n+1), 256]) {c, newdict, 258}

     if s!=[], s*c is not in the domain of d, and hibit(n+2) > 12.

   {s,d,n} (input EOD) ---> (emit[hibit(n), d(s)]) (emit[hibit(n+1), 257]) stop

     where s != []. Here, EOD stands for end-of-data.

   {[],d,n} (input EOD) ---> (emit[hibit(n), 256]) (emit[hibit(n), 257]) stop

   Notes: 

   * Each reachable state {s,d,n} satisfies hibit(n+1) <= 12.
   * Only codes of 12 or fewer bits are emitted.
   * Each reachable state {s,d,n} satisfies s=[] or s is in the domain of d.
   * The domain of d is always prefix closed (except for the empty prefix)
   * The state machine is deterministic and non-blocking.

*/
   

/* ---------------------------------------------------------------------- */
/* private state */

#define BITBUF_TYPE unsigned int

/* the dictionary is implemented as a tree of strings under the prefix
   order. The tree is in turns represented as a linked list of
   lzw_dict_t structures, with "children" pointing to a node's first
   child, and "next" pointing to a node's next sibling. As an
   optimization, the top-level nodes (singleton strings) are
   implemented lazily, i.e., the corresponding entry is not actually
   created until it is accessed. */

struct lzw_dict_s {
  char c;      /* last character of string represented by this entry */
  int code;    /* code for the string represented by this entry */
  int freq;    /* how often searched? For optimization only */
  struct lzw_dict_s *children;  /* list of sub-entries */
  struct lzw_dict_s *next;      /* for making a linked list */
};
typedef struct lzw_dict_s lzw_dict_t;

/* A state {s,d,n} is represented by the "dictionary state" part of
   the lzw_state_t structure. Here, s is a pointer directly to the node
   of the dictionary structure corresponding to the string s, or NULL
   if s=[]. Further, the lzw_state_t structure contains a buffer of
   pending output bits, and a flag indicating whether the EOD (end of
   data) has been reached in the input. */

struct lzw_state_s {
  /* dictionary state */
  int n;           /* current size of the dictionary */
  lzw_dict_t *d;     /* pointer to dictionary */
  lzw_dict_t *s;     /* pointer to current string, or NULL at beginning */

  /* buffers for pending output */
  BITBUF_TYPE buf; /* bits scheduled for output - left aligned, 0 padded */
  int bufsize;     /* number of bits scheduled for output. */
  int eod;         /* flush buffer? */
};
typedef struct lzw_state_s lzw_state_t;

/* ---------------------------------------------------------------------- */
/* auxiliary functions which operate on dictionary states */

/* recursively free an lzw_dict_t object */
static void lzw_free_dict(lzw_dict_t *s) {
  lzw_dict_t *e;

  list_forall_unlink(e, s) {
    lzw_free_dict(e->children);
    free(e);
  }
}

/* re-initialize the lzw state's dictionary state to "newdict",
   freeing any old dictionary. */
static void lzw_clear_table(lzw_state_t *st) {

  lzw_free_dict(st->d);
  st->d = NULL;
  st->n = 258;
  st->s = NULL;
}

/* ---------------------------------------------------------------------- */
/* auxiliary functions for reading/writing the bit buffer */

/* write the code to the bit buffer. Precondition st->bufsize <= 7.
   Note: this does not change the dictionary state; in particular,
   n must be updated between consecutive calls. */
static inline void lzw_emit(int code, lzw_state_t *st) {
  BITBUF_TYPE mask;
  int bits = hibit(st->n);

  /* fill bit buffer */
  mask = (1 << bits) - 1;
  code &= mask;

  st->buf |= code << (8*sizeof(BITBUF_TYPE) - st->bufsize - bits);
  st->bufsize += bits;
}

/* transfer one byte from bit buffer to output. Precondition:
   s->avail_out > 0. */
static inline void lzw_read_bitbuf(lzw_stream_t *s) {
  int ch;
  lzw_state_t *st = (lzw_state_t *)s->internal;

  ch = st->buf >> (8*sizeof(BITBUF_TYPE)-8);
  st->buf <<= 8;
  st->bufsize -= 8;

  s->next_out[0] = ch;
  s->next_out++;
  s->avail_out--;
}

/* ---------------------------------------------------------------------- */
/* The following functions implement the state machine. */

/* perform state transition of the state st on input character
   ch. This updates the dictionary state and/or writes to the bit
   buffer. Precondition: st->bufsize <= 7. Return 0 on success, or 1
   on error with errno set. */
static int lzw_encode_char(lzw_state_t *st, char c) {
  lzw_dict_t *e;

  /* st = {s,d,n}. hibit(n+1)<=12. */

  /* {[], d, n} (input c) ---> (emit[hibit(n), 256]) {c, d, n} */
  if (st->s == NULL) {
    lzw_emit(256, st);
    goto singleton;  /* enter singleton state c */
  } 

  /* {s,d,n} (input c) ---> {s*c,d,n} */
  list_find(e, st->s->children, e->c == c);
  if (e) {
    e->freq++;
    st->s = e;
    return 0;
  }

  /* {s,d,n} (input c) ---> (emit[hibit(n), d(s)]) {c,d',n+1} */
  /* {s,d,n} (input c) --->
	    (emit[hibit(n), d(s)]) (emit[hibit(n+1), 256]) {c, newdict, 258} */

  lzw_emit(st->s->code, st); /* 9-12 bits */
  if (st->n >= 4094) {   /* hibit(n+2) > 12 */
    st->n++;
    lzw_emit(256, st);
    goto dictfull;    /* reset dictionary and enter singleton state c */
  }

  /* insert new code in dictionary, if possible */
  e = (lzw_dict_t *)malloc(sizeof(lzw_dict_t));
  if (!e) {
    return 1;
  }
  e->c = c;
  e->code = st->n;
  e->freq = 1;
  e->children = NULL;
  list_prepend(st->s->children, e);
  st->n++;
  goto singleton;  /* enter singleton state c */

 dictfull:    /* reset dictionary and enter singleton state c */
  lzw_clear_table(st);
  /* fall through */
  
 singleton:   /* enter singleton state c */
  list_find(e, st->d, e->c == c);
  if (!e) {  /* not found: lazily add it */
    e = (lzw_dict_t *)malloc(sizeof(lzw_dict_t));
    if (!e) {
      return 1;
    }
    e->c = c;
    e->code = (int)(unsigned char)c;
    e->freq = 0;
    e->children = NULL;
    list_prepend(st->d, e);
  }
  e->freq++;
  st->s = e;
  return 0;
}

/* perform state transition of the state st on input EOD. The leaves
   the dictionary state undefined and writes to the bit buffer.
   Precondition: st->bufsize <= 7. This function must be called
   exactly once, at the end of the stream. */
static void lzw_encode_eod(lzw_state_t *st) {

  /* {[],d,n} (input EOD) ---> 
              (emit[hibit(n), 256]) (emit[hibit(n), 257]) stop */
  if (st->s == NULL) {
    lzw_emit(256, st);  /* 9 bits */
    st->n=258;
    lzw_emit(257, st);  /* 9 bits */
    return;
  } 

  /* {s,d,n} (input EOD) ---> 
             (emit[hibit(n), code]) (emit[hibit(n+1), 257]) stop */

  lzw_emit(st->s->code, st); /* 9-12 bits */
  st->n++;
  lzw_emit(257, st);  /* 9-12 bits */
  return;
}

/* ---------------------------------------------------------------------- */
/* User visible functions. These implement a buffer interface. See
   lzw.h for the API description. */

lzw_stream_t *lzw_init(void) {
  lzw_stream_t *s = NULL;
  lzw_state_t *st = NULL;

  s = (lzw_stream_t *)malloc(sizeof(lzw_stream_t));
  if (s==NULL) {
    goto fail;
  }
  st = (lzw_state_t *)malloc(sizeof(lzw_state_t));
  if (st==NULL) {
    goto fail;
  }
  st->buf = 0;
  st->bufsize = 0;
  st->eod = 0;
  st->d = NULL;
  lzw_clear_table(st);
  s->internal = (void *) st;
  return s;

 fail:
  free(s);
  free(st);
  return NULL;
}

int lzw_compress(lzw_stream_t *s, int mode) {
  int r;
  lzw_state_t *st = (lzw_state_t *)s->internal;

  while (st->eod == 0) {
    /* empty bit buffer */
    while (st->bufsize > 7) {
      if (s->avail_out == 0) {
	return 0;
      } else {
	lzw_read_bitbuf(s);
      }
    }
    /* fill bit buffer */
    if (s->avail_in == 0) {
      break;
    } else {
      r = lzw_encode_char(st, s->next_in[0]);
      if (r) {
	if (r==2) {
	  errno = EINVAL;
	}
	return 1;
      }
      s->next_in++;
      s->avail_in--;
    }
  }

  if (mode==LZW_EOD && st->eod == 0) {
    st->eod = 1;
    lzw_encode_eod(st);
  }

  /* flush bit buffer */
  if (st->eod) {
    while (st->bufsize > 0) {
      if (s->avail_out == 0) {
	return 0;
      } else {
	lzw_read_bitbuf(s);
      }
    }
  }

  return 0;
}

void lzw_free(lzw_stream_t *s) {
  lzw_state_t *st = (lzw_state_t *)s->internal;

  lzw_free_dict(st->d);
  free(st);
  free(s);
}

/* ---------------------------------------------------------------------- */
/* main function for testing and illustration purposes */

#ifdef LZW_MAIN

int main() {
  lzw_stream_t *s;
  int ch;
  char inbuf[100];
  char outbuf[100];
  int i, r;
  int mode;

  s = lzw_init();
  if (!s) {
    goto error;
  }
  mode = LZW_NORMAL;

  while (1) {
    /* fill inbuf */
    for (i=0; i<100; i++) {
      ch = fgetc(stdin);
      if (ch==EOF) {
	break;
      }
      inbuf[i] = ch;
    }
    if (i<100) {   /* end of input */
      mode = LZW_EOD;
    }

    /* compress */
    s->next_in = inbuf;
    s->avail_in = i;
    do {
      s->next_out = outbuf;
      s->avail_out = 100;
      r = lzw_compress(s, mode);
      if (r) {
	goto error;
      }
      fwrite(outbuf, 1, 100-s->avail_out, stdout);
    } while (s->avail_out==0);
    if (mode == LZW_EOD) {
      break;
    }
  }
  fflush(stdout);
  lzw_free(s);

  return 0;

 error:
  fprintf(stderr, "lzw: %s\n", strerror(errno));
  lzw_free(s);
  return 1;

}
#endif