1 /* deflate.c -- compress data using the deflation algorithm
2 * Copyright (C) 1992-1993 Jean-loup Gailly
3 * This is free software; you can redistribute it and/or modify it under the
4 * terms of the GNU General Public License, see the file COPYING.
10 * Identify new text as repetitions of old text within a fixed-
11 * length sliding window trailing behind the new text.
15 * The "deflation" process depends on being able to identify portions
16 * of the input text which are identical to earlier input (within a
17 * sliding window trailing behind the input currently being processed).
19 * The most straightforward technique turns out to be the fastest for
20 * most input files: try all possible matches and select the longest.
21 * The key feature of this algorithm is that insertions into the string
22 * dictionary are very simple and thus fast, and deletions are avoided
23 * completely. Insertions are performed at each input character, whereas
24 * string matches are performed only when the previous match ends. So it
25 * is preferable to spend more time in matches to allow very fast string
26 * insertions and avoid deletions. The matching algorithm for small
27 * strings is inspired from that of Rabin & Karp. A brute force approach
28 * is used to find longer strings when a small match has been found.
29 * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
30 * (by Leonid Broukhis).
31 * A previous version of this file used a more sophisticated algorithm
32 * (by Fiala and Greene) which is guaranteed to run in linear amortized
33 * time, but has a larger average cost, uses more memory and is patented.
34 * However the F&G algorithm may be faster for some highly redundant
35 * files if the parameter max_chain_length (described below) is too large.
39 * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
40 * I found it in 'freeze' written by Leonid Broukhis.
41 * Thanks to many info-zippers for bug reports and testing.
45 * APPNOTE.TXT documentation file in PKZIP 1.93a distribution.
47 * A description of the Rabin and Karp algorithm is given in the book
48 * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
50 * Fiala,E.R., and Greene,D.H.
51 * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
55 * void lm_init (int pack_level, ush *flags)
56 * Initialize the "longest match" routines for a new file
58 * off_t deflate (void)
59 * Processes a new input file and return its compressed length. Sets
60 * the compressed length, crc, deflate flags and internal file
69 #include "lzw.h" /* just for consistency checking */
72 static char rcsid[] = "$Id$";
75 /* ===========================================================================
76 * Configuration parameters
79 /* Compile with MEDIUM_MEM to reduce the memory requirements or
80 * with SMALL_MEM to use as little memory as possible. Use BIG_MEM if the
81 * entire input file can be held in memory (not possible on 16 bit systems).
82 * Warning: defining these symbols affects HASH_BITS (see below) and thus
83 * affects the compression ratio. The compressed output
84 * is still correct, and might even be smaller in some cases.
88 # define HASH_BITS 13 /* Number of bits used to hash strings */
95 /* For portability to 16 bit machines, do not use values above 15. */
98 /* To save space (see unlzw.c), we overlay prev+head with tab_prefix and
99 * window with tab_suffix. Check that we can do this:
101 #if (WSIZE<<1) > (1<<BITS)
102 error: cannot overlay window with tab_suffix and prev with tab_prefix0
104 #if HASH_BITS > BITS-1
105 error: cannot overlay head with tab_prefix1
108 #define HASH_SIZE (unsigned)(1<<HASH_BITS)
109 #define HASH_MASK (HASH_SIZE-1)
110 #define WMASK (WSIZE-1)
111 /* HASH_SIZE and WSIZE must be powers of two */
114 /* Tail of hash chains */
118 /* speed options for the general purpose bit flag */
121 # define TOO_FAR 4096
123 /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
125 /* ===========================================================================
126 * Local data used by the "longest match" routines.
130 typedef unsigned IPos;
131 /* A Pos is an index in the character window. We use short instead of int to
132 * save space in the various tables. IPos is used only for parameter passing.
135 /* DECLARE(uch, window, 2L*WSIZE); */
136 /* Sliding window. Input bytes are read into the second half of the window,
137 * and move to the first half later to keep a dictionary of at least WSIZE
138 * bytes. With this organization, matches are limited to a distance of
139 * WSIZE-MAX_MATCH bytes, but this ensures that IO is always
140 * performed with a length multiple of the block size. Also, it limits
141 * the window size to 64K, which is quite useful on MSDOS.
142 * To do: limit the window size to WSIZE+BSZ if SMALL_MEM (the code would
143 * be less efficient).
146 /* DECLARE(Pos, prev, WSIZE); */
147 /* Link to older string with same hash index. To limit the size of this
148 * array to 64K, this link is maintained only for the last 32K strings.
149 * An index in this array is thus a window index modulo 32K.
152 /* DECLARE(Pos, head, 1<<HASH_BITS); */
153 /* Heads of the hash chains or NIL. */
155 ulg window_size = (ulg)2*WSIZE;
156 /* window size, 2*WSIZE except for MMAP or BIG_MEM, where it is the
157 * input file length plus MIN_LOOKAHEAD.
161 /* window position at the beginning of the current output block. Gets
162 * negative when the window is moved backwards.
165 local unsigned ins_h; /* hash index of string to be inserted */
167 #define H_SHIFT ((HASH_BITS+MIN_MATCH-1)/MIN_MATCH)
168 /* Number of bits by which ins_h and del_h must be shifted at each
169 * input step. It must be such that after MIN_MATCH steps, the oldest
170 * byte no longer takes part in the hash key, that is:
171 * H_SHIFT * MIN_MATCH >= HASH_BITS
174 unsigned int near prev_length;
175 /* Length of the best match at previous step. Matches not greater than this
176 * are discarded. This is used in the lazy match evaluation.
179 unsigned near strstart; /* start of string to insert */
180 unsigned near match_start; /* start of matching string */
181 local int eofile; /* flag set at end of input file */
182 local unsigned lookahead; /* number of valid bytes ahead in window */
184 unsigned near max_chain_length;
185 /* To speed up deflation, hash chains are never searched beyond this length.
186 * A higher limit improves compression ratio but degrades the speed.
189 local unsigned int max_lazy_match;
190 /* Attempt to find a better match only when the current match is strictly
191 * smaller than this value. This mechanism is used only for compression
194 #define max_insert_length max_lazy_match
195 /* Insert new strings in the hash table only if the match length
196 * is not greater than this length. This saves time but degrades compression.
197 * max_insert_length is used only for compression levels <= 3.
200 local int compr_level;
201 /* compression level (1..9) */
203 unsigned near good_match;
204 /* Use a faster search when the previous match is longer than this */
207 /* Values for max_lazy_match, good_match and max_chain_length, depending on
208 * the desired pack level (0..9). The values given below have been tuned to
209 * exclude worst case performance for pathological files. Better values may be
210 * found for specific files.
213 typedef struct config {
214 ush good_length; /* reduce lazy search above this match length */
215 ush max_lazy; /* do not perform lazy search above this match length */
216 ush nice_length; /* quit search above this match length */
221 # define nice_match MAX_MATCH
223 int near nice_match; /* Stop searching when current match exceeds this */
226 local config configuration_table[10] = {
227 /* good lazy nice chain */
228 /* 0 */ {0, 0, 0, 0}, /* store only */
229 /* 1 */ {4, 4, 8, 4}, /* maximum speed, no lazy matches */
230 /* 2 */ {4, 5, 16, 8},
231 /* 3 */ {4, 6, 32, 32},
233 /* 4 */ {4, 4, 16, 16}, /* lazy matches */
234 /* 5 */ {8, 16, 32, 32},
235 /* 6 */ {8, 16, 128, 128},
236 /* 7 */ {8, 32, 128, 256},
237 /* 8 */ {32, 128, 258, 1024},
238 /* 9 */ {32, 258, 258, 4096}}; /* maximum compression */
240 /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
241 * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
246 /* result of memcmp for equal strings */
248 /* ===========================================================================
249 * Prototypes for local functions.
251 local void fill_window OF((void));
252 local off_t deflate_fast OF((void));
254 int longest_match OF((IPos cur_match));
256 void match_init OF((void)); /* asm code initialization */
260 local void check_match OF((IPos start, IPos match, int length));
263 /* ===========================================================================
264 * Update a hash value with the given input byte
265 * IN assertion: all calls to to UPDATE_HASH are made with consecutive
266 * input characters, so that a running hash key can be computed from the
267 * previous key instead of complete recalculation each time.
269 #define UPDATE_HASH(h,c) (h = (((h)<<H_SHIFT) ^ (c)) & HASH_MASK)
271 /* ===========================================================================
272 * Insert string s in the dictionary and set match_head to the previous head
273 * of the hash chain (the most recent string with same hash key). Return
274 * the previous length of the hash chain.
275 * IN assertion: all calls to to INSERT_STRING are made with consecutive
276 * input characters and the first MIN_MATCH bytes of s are valid
277 * (except for the last MIN_MATCH-1 bytes of the input file).
279 #define INSERT_STRING(s, match_head) \
280 (UPDATE_HASH(ins_h, window[(s) + MIN_MATCH-1]), \
281 prev[(s) & WMASK] = match_head = head[ins_h], \
284 /* ===========================================================================
285 * Initialize the "longest match" routines for a new file
287 void lm_init (pack_level, flags)
288 int pack_level; /* 0: store, 1: best speed, 9: best compression */
289 ush *flags; /* general purpose bit flag */
293 if (pack_level < 1 || pack_level > 9) error("bad pack level");
294 compr_level = pack_level;
296 /* Initialize the hash table. */
297 #if defined(MAXSEG_64K) && HASH_BITS == 15
298 for (j = 0; j < HASH_SIZE; j++) head[j] = NIL;
300 memzero((char*)head, HASH_SIZE*sizeof(*head));
302 /* prev will be initialized on the fly */
304 /* Set the default configuration parameters:
306 max_lazy_match = configuration_table[pack_level].max_lazy;
307 good_match = configuration_table[pack_level].good_length;
309 nice_match = configuration_table[pack_level].nice_length;
311 max_chain_length = configuration_table[pack_level].max_chain;
312 if (pack_level == 1) {
314 } else if (pack_level == 9) {
317 /* ??? reduce max_chain_length for binary files */
322 match_init(); /* initialize the asm code */
325 lookahead = read_buf((char*)window,
326 sizeof(int) <= 2 ? (unsigned)WSIZE : 2*WSIZE);
328 if (lookahead == 0 || lookahead == (unsigned)EOF) {
329 eofile = 1, lookahead = 0;
333 /* Make sure that we always have enough lookahead. This is important
334 * if input comes from a device such as a tty.
336 while (lookahead < MIN_LOOKAHEAD && !eofile) fill_window();
339 for (j=0; j<MIN_MATCH-1; j++) UPDATE_HASH(ins_h, window[j]);
340 /* If lookahead < MIN_MATCH, ins_h is garbage, but this is
341 * not important since only literal bytes will be emitted.
345 /* ===========================================================================
346 * Set match_start to the longest match starting at the given string and
347 * return its length. Matches shorter or equal to prev_length are discarded,
348 * in which case the result is equal to prev_length and match_start is
350 * IN assertions: cur_match is the head of the hash chain for the current
351 * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
354 /* For MSDOS, OS/2 and 386 Unix, an optimized version is in match.asm or
355 * match.s. The code is functionally equivalent, so you can use the C version
358 int longest_match(cur_match)
359 IPos cur_match; /* current match */
361 unsigned chain_length = max_chain_length; /* max hash chain length */
362 register uch *scan = window + strstart; /* current string */
363 register uch *match; /* matched string */
364 register int len; /* length of current match */
365 int best_len = prev_length; /* best match length so far */
366 IPos limit = strstart > (IPos)MAX_DIST ? strstart - (IPos)MAX_DIST : NIL;
367 /* Stop when cur_match becomes <= limit. To simplify the code,
368 * we prevent matches with the string of window index 0.
371 /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
372 * It is easy to get rid of this optimization if necessary.
374 #if HASH_BITS < 8 || MAX_MATCH != 258
375 error: Code too clever
379 /* Compare two bytes at a time. Note: this is not always beneficial.
380 * Try with and without -DUNALIGNED_OK to check.
382 register uch *strend = window + strstart + MAX_MATCH - 1;
383 register ush scan_start = *(ush*)scan;
384 register ush scan_end = *(ush*)(scan+best_len-1);
386 register uch *strend = window + strstart + MAX_MATCH;
387 register uch scan_end1 = scan[best_len-1];
388 register uch scan_end = scan[best_len];
391 /* Do not waste too much time if we already have a good match: */
392 if (prev_length >= good_match) {
395 Assert(strstart <= window_size-MIN_LOOKAHEAD, "insufficient lookahead");
398 Assert(cur_match < strstart, "no future");
399 match = window + cur_match;
401 /* Skip to next match if the match length cannot increase
402 * or if the match length is less than 2:
404 #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
405 /* This code assumes sizeof(unsigned short) == 2. Do not use
406 * UNALIGNED_OK if your compiler uses a different size.
408 if (*(ush*)(match+best_len-1) != scan_end ||
409 *(ush*)match != scan_start) continue;
411 /* It is not necessary to compare scan[2] and match[2] since they are
412 * always equal when the other bytes match, given that the hash keys
413 * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
414 * strstart+3, +5, ... up to strstart+257. We check for insufficient
415 * lookahead only every 4th comparison; the 128th check will be made
416 * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
417 * necessary to put more guard bytes at the end of the window, or
418 * to check more often for insufficient lookahead.
422 } while (*(ush*)(scan+=2) == *(ush*)(match+=2) &&
423 *(ush*)(scan+=2) == *(ush*)(match+=2) &&
424 *(ush*)(scan+=2) == *(ush*)(match+=2) &&
425 *(ush*)(scan+=2) == *(ush*)(match+=2) &&
427 /* The funny "do {}" generates better code on most compilers */
429 /* Here, scan <= window+strstart+257 */
430 Assert(scan <= window+(unsigned)(window_size-1), "wild scan");
431 if (*scan == *match) scan++;
433 len = (MAX_MATCH - 1) - (int)(strend-scan);
434 scan = strend - (MAX_MATCH-1);
436 #else /* UNALIGNED_OK */
438 if (match[best_len] != scan_end ||
439 match[best_len-1] != scan_end1 ||
441 *++match != scan[1]) continue;
443 /* The check at best_len-1 can be removed because it will be made
444 * again later. (This heuristic is not always a win.)
445 * It is not necessary to compare scan[2] and match[2] since they
446 * are always equal when the other bytes match, given that
447 * the hash keys are equal and that HASH_BITS >= 8.
451 /* We check for insufficient lookahead only every 8th comparison;
452 * the 256th check will be made at strstart+258.
455 } while (*++scan == *++match && *++scan == *++match &&
456 *++scan == *++match && *++scan == *++match &&
457 *++scan == *++match && *++scan == *++match &&
458 *++scan == *++match && *++scan == *++match &&
461 len = MAX_MATCH - (int)(strend - scan);
462 scan = strend - MAX_MATCH;
464 #endif /* UNALIGNED_OK */
466 if (len > best_len) {
467 match_start = cur_match;
469 if (len >= nice_match) break;
471 scan_end = *(ush*)(scan+best_len-1);
473 scan_end1 = scan[best_len-1];
474 scan_end = scan[best_len];
477 } while ((cur_match = prev[cur_match & WMASK]) > limit
478 && --chain_length != 0);
485 /* ===========================================================================
486 * Check that the match at match_start is indeed a match.
488 local void check_match(start, match, length)
492 /* check that the match is indeed a match */
493 if (memcmp((char*)window + match,
494 (char*)window + start, length) != EQUAL) {
496 " start %d, match %d, length %d\n",
497 start, match, length);
498 error("invalid match");
501 fprintf(stderr,"\\[%d,%d]", start-match, length);
502 do { putc(window[start++], stderr); } while (--length != 0);
506 # define check_match(start, match, length)
509 /* ===========================================================================
510 * Fill the window when the lookahead becomes insufficient.
511 * Updates strstart and lookahead, and sets eofile if end of input file.
512 * IN assertion: lookahead < MIN_LOOKAHEAD && strstart + lookahead > 0
513 * OUT assertions: at least one byte has been read, or eofile is set;
514 * file reads are performed for at least two bytes (required for the
515 * translate_eol option).
517 local void fill_window()
519 register unsigned n, m;
520 unsigned more = (unsigned)(window_size - (ulg)lookahead - (ulg)strstart);
521 /* Amount of free space at the end of the window. */
523 /* If the window is almost full and there is insufficient lookahead,
524 * move the upper half to the lower one to make room in the upper half.
526 if (more == (unsigned)EOF) {
527 /* Very unlikely, but possible on 16 bit machine if strstart == 0
528 * and lookahead == 1 (input done one byte at time)
531 } else if (strstart >= WSIZE+MAX_DIST) {
532 /* By the IN assertion, the window is not empty so we can't confuse
533 * more == 0 with more == 64K on a 16 bit machine.
535 Assert(window_size == (ulg)2*WSIZE, "no sliding with BIG_MEM");
537 memcpy((char*)window, (char*)window+WSIZE, (unsigned)WSIZE);
538 match_start -= WSIZE;
539 strstart -= WSIZE; /* we now have strstart >= MAX_DIST: */
541 block_start -= (long) WSIZE;
543 for (n = 0; n < HASH_SIZE; n++) {
545 head[n] = (Pos)(m >= WSIZE ? m-WSIZE : NIL);
547 for (n = 0; n < WSIZE; n++) {
549 prev[n] = (Pos)(m >= WSIZE ? m-WSIZE : NIL);
550 /* If n is not on any hash chain, prev[n] is garbage but
551 * its value will never be used.
556 /* At this point, more >= 2 */
558 n = read_buf((char*)window+strstart+lookahead, more);
559 if (n == 0 || n == (unsigned)EOF) {
567 /* ===========================================================================
568 * Flush the current block, with given end-of-file flag.
569 * IN assertion: strstart is set to the end of the current match.
571 #define FLUSH_BLOCK(eof) \
572 flush_block(block_start >= 0L ? (char*)&window[(unsigned)block_start] : \
573 (char*)NULL, (long)strstart - block_start, (eof))
575 /* ===========================================================================
576 * Processes a new input file and return its compressed length. This
577 * function does not perform lazy evaluationof matches and inserts
578 * new strings in the dictionary only for unmatched strings or for short
579 * matches. It is used only for the fast compression options.
581 local off_t deflate_fast()
583 IPos hash_head; /* head of the hash chain */
584 int flush; /* set if current block must be flushed */
585 unsigned match_length = 0; /* length of best match */
587 prev_length = MIN_MATCH-1;
588 while (lookahead != 0) {
589 /* Insert the string window[strstart .. strstart+2] in the
590 * dictionary, and set hash_head to the head of the hash chain:
592 INSERT_STRING(strstart, hash_head);
594 /* Find the longest match, discarding those <= prev_length.
595 * At this point we have always match_length < MIN_MATCH
597 if (hash_head != NIL && strstart - hash_head <= MAX_DIST) {
598 /* To simplify the code, we prevent matches with the string
599 * of window index 0 (in particular we have to avoid a match
600 * of the string with itself at the start of the input file).
602 match_length = longest_match (hash_head);
603 /* longest_match() sets match_start */
604 if (match_length > lookahead) match_length = lookahead;
606 if (match_length >= MIN_MATCH) {
607 check_match(strstart, match_start, match_length);
609 flush = ct_tally(strstart-match_start, match_length - MIN_MATCH);
611 lookahead -= match_length;
613 /* Insert new strings in the hash table only if the match length
614 * is not too large. This saves time but degrades compression.
616 if (match_length <= max_insert_length) {
617 match_length--; /* string at strstart already in hash table */
620 INSERT_STRING(strstart, hash_head);
621 /* strstart never exceeds WSIZE-MAX_MATCH, so there are
622 * always MIN_MATCH bytes ahead. If lookahead < MIN_MATCH
623 * these bytes are garbage, but it does not matter since
624 * the next lookahead bytes will be emitted as literals.
626 } while (--match_length != 0);
629 strstart += match_length;
631 ins_h = window[strstart];
632 UPDATE_HASH(ins_h, window[strstart+1]);
634 Call UPDATE_HASH() MIN_MATCH-3 more times
638 /* No match, output a literal byte */
639 Tracevv((stderr,"%c",window[strstart]));
640 flush = ct_tally (0, window[strstart]);
644 if (flush) FLUSH_BLOCK(0), block_start = strstart;
646 /* Make sure that we always have enough lookahead, except
647 * at the end of the input file. We need MAX_MATCH bytes
648 * for the next match, plus MIN_MATCH bytes to insert the
649 * string following the next match.
651 while (lookahead < MIN_LOOKAHEAD && !eofile) fill_window();
654 return FLUSH_BLOCK(1); /* eof */
657 /* ===========================================================================
658 * Same as above, but achieves better compression. We use a lazy
659 * evaluation for matches: a match is finally adopted only if there is
660 * no better match at the next window position.
664 IPos hash_head; /* head of hash chain */
665 IPos prev_match; /* previous match */
666 int flush; /* set if current block must be flushed */
667 int match_available = 0; /* set if previous match exists */
668 register unsigned match_length = MIN_MATCH-1; /* length of best match */
670 if (compr_level <= 3) return deflate_fast(); /* optimized for speed */
672 /* Process the input block. */
673 while (lookahead != 0) {
674 /* Insert the string window[strstart .. strstart+2] in the
675 * dictionary, and set hash_head to the head of the hash chain:
677 INSERT_STRING(strstart, hash_head);
679 /* Find the longest match, discarding those <= prev_length.
681 prev_length = match_length, prev_match = match_start;
682 match_length = MIN_MATCH-1;
684 if (hash_head != NIL && prev_length < max_lazy_match &&
685 strstart - hash_head <= MAX_DIST) {
686 /* To simplify the code, we prevent matches with the string
687 * of window index 0 (in particular we have to avoid a match
688 * of the string with itself at the start of the input file).
690 match_length = longest_match (hash_head);
691 /* longest_match() sets match_start */
692 if (match_length > lookahead) match_length = lookahead;
694 /* Ignore a length 3 match if it is too distant: */
695 if (match_length == MIN_MATCH && strstart-match_start > TOO_FAR){
696 /* If prev_match is also MIN_MATCH, match_start is garbage
697 * but we will ignore the current match anyway.
702 /* If there was a match at the previous step and the current
703 * match is not better, output the previous match:
705 if (prev_length >= MIN_MATCH && match_length <= prev_length) {
707 check_match(strstart-1, prev_match, prev_length);
709 flush = ct_tally(strstart-1-prev_match, prev_length - MIN_MATCH);
711 /* Insert in hash table all strings up to the end of the match.
712 * strstart-1 and strstart are already inserted.
714 lookahead -= prev_length-1;
718 INSERT_STRING(strstart, hash_head);
719 /* strstart never exceeds WSIZE-MAX_MATCH, so there are
720 * always MIN_MATCH bytes ahead. If lookahead < MIN_MATCH
721 * these bytes are garbage, but it does not matter since the
722 * next lookahead bytes will always be emitted as literals.
724 } while (--prev_length != 0);
726 match_length = MIN_MATCH-1;
728 if (flush) FLUSH_BLOCK(0), block_start = strstart;
730 } else if (match_available) {
731 /* If there was no match at the previous position, output a
732 * single literal. If there was a match but the current match
733 * is longer, truncate the previous match to a single literal.
735 Tracevv((stderr,"%c",window[strstart-1]));
736 if (ct_tally (0, window[strstart-1])) {
737 FLUSH_BLOCK(0), block_start = strstart;
742 /* There is no previous match to compare with, wait for
743 * the next step to decide.
749 Assert (strstart <= bytes_in && lookahead <= bytes_in, "a bit too far");
751 /* Make sure that we always have enough lookahead, except
752 * at the end of the input file. We need MAX_MATCH bytes
753 * for the next match, plus MIN_MATCH bytes to insert the
754 * string following the next match.
756 while (lookahead < MIN_LOOKAHEAD && !eofile) fill_window();
758 if (match_available) ct_tally (0, window[strstart-1]);
760 return FLUSH_BLOCK(1); /* eof */