-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathdeflate.c
1711 lines (1466 loc) · 55.5 KB
/
deflate.c
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* deflate.c -- compress data using the deflation algorithm
* Copyright (C) 1995-1998 Jean-loup Gailly.
* For conditions of distribution and use, see copyright notice in zlib.h
file modified by Dimitre Trendafilov (2003)
*/
/*
* zdelta: the algorithm description is slightly changed from the original
* in zlib in order to match better zdelta deflation process.
*
* ALGORITHM
*
* The "deflation" process depends on being able to identify portions
* of the input text which are identical to earlier input (within a
* sliding window trailing behind the input currently being processed),
* or to reference data (within a separate sliding window, which movement
* is based on weighted average of the most recently used matches).
*
* The most straightforward technique turns out to be the fastest for
* most input files: try all possible matches and select the longest one
* (if there is more than one matches with such length, a chose the match
* resulting in the smallest match offset).
* The key feature of this algorithm is that insertions into the string
* dictionaries (one for the already processed input, and one for the
* reference data) are very simple and thus fast, and deletions are
* avoided completely. Insertions are performed at each input character,
* whereas string matches are performed only when the previous match
* ends. So it is preferable to spend more time in matches to allow very
* fast string insertions and avoid deletions. The matching algorithm for
* small strings is inspired from that of Rabin & Karp. A brute force
* approach is used to find longer strings when a small match has been
* found. A similar algorithm is used in comic (by Jan-Mark Wams) and
* freeze (by Leonid Broukhis).
*
* ACKNOWLEDGEMENTS
*
* The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
* I found it in 'freeze' written by Leonid Broukhis.
* Thanks to many people for bug reports and testing.
*
* REFERENCES
*
* Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
* Available in ftp://ds.internic.net/rfc/rfc1951.txt
*
* A description of the Rabin and Karp algorithm is given in the book
* "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
*
* Fiala,E.R., and Greene,D.H.
* Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
*
*/
/* zdelta:
*
* modified:
* deflate() -- added prefix zd
* deflateEnd() -- added prefix zd
* deflateInit2_() -- added prefix zd
* deflateReset() -- added prefix zd
* lm_init()
* longest_match()
* deflate_stored()
* added:
* delta_deflate_fast()
* delta_deflate_slow()
* fill_ref_window()
* init_ref_window()
* init_window()
* read_ref_buf()
* reference_longest_match()
* removed:
* check_match()
* deflate_copy()
* deflate_fast()
* deflate_slow()
* deflateSetDictionary()
*/
/* @(#) $Id$ */
#include "deflate.h"
#include <limits.h>
const char zd_deflate_copyright[] =
" deflate 1.1.3 Copyright 1995-1998 Jean-loup Gailly ";
/*
zdelta: zd prefix added.
If you use the zlib library in a product, an acknowledgment is welcome
in the documentation of your product. If for some reason you cannot
include such an acknowledgment, I would appreciate that you keep this
copyright string in the executable of your product.
*/
/* ===========================================================================
* Function prototypes.
*/
typedef enum {
need_more, /* block not completed, need more input or more output */
block_done, /* block flush performed */
finish_started, /* finish started, need only more output at next deflate */
finish_done /* finish done, accept no more input or output */
} block_state;
typedef block_state (*compress_func) OF((deflate_state *s, int flush));
/* Compression function. Returns the block state after the call. */
local void fill_window OF((deflate_state *s));
local void fill_ref_window OF((deflate_state *s, int rw)); /* zdelta: added */
local void lm_init OF((deflate_state *s)); /* zdelta: modified */
local void init_window OF((deflate_state *s)); /* zdelta: added */
local void init_ref_window OF((deflate_state *s, int rw)); /* zdelta: added */
local block_state deflate_stored OF((deflate_state *s, int flush));
/* zdelta: added */
local block_state delta_deflate_fast OF((deflate_state *s, int flush));
local block_state delta_deflate_slow OF((deflate_state *s, int flush));
local void putShortMSB OF((deflate_state *s, uInt b));
local void flush_pending OF((zd_streamp strm));
local int read_buf OF((zd_streamp strm, Bytef *buf, unsigned size));
/* zdelta: added */
local int read_ref_buf OF((zd_streamp strm, Bytef *buf, unsigned size, int rw));
local void target_longest_match OF((deflate_state *s, IPos cur_match));
local void reference_longest_match OF((deflate_state *s,
IPos cur_match, int rw));
/* ===========================================================================
* Local data
*/
#define NIL 0
/* Tail of hash chains */
#define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
/* Minimum amount of lookahead, except at the end of the input file.
* See deflate.c for comments about the MIN_MATCH+1.
*/
/* Values for max_lazy_match, good_match and max_chain_length, depending on
* the desired pack level (0..9). The values given below have been tuned to
* exclude worst case performance for pathological files. Better values may be
* found for specific files.
*/
typedef struct config_s {
ush good_length; /* reduce search above this match length */
ush max_lazy; /* do not perform lazy search above this match length */
ush nice_length; /* quit search above this match length */
ush max_chain;
compress_func func;
} config;
local const config configuration_table[10] = {
/* good lazy nice chain */
/* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
/* 1 */ {64, 64, 128, 4, delta_deflate_fast}, /* maximum speed .. */
/* 2 */ {64, 80, 256, 8, delta_deflate_fast}, /* .. no lazy matches */
/* 3 */ {64, 96, 512, 32, delta_deflate_fast},
/* 4 */ {64, 64, 256, 16, delta_deflate_slow}, /* lazy matches */
/* 5 */ {128, 256, 512, 32, delta_deflate_slow},
/* 6 */ {128, 256, 2048, 128, delta_deflate_slow},
/* 7 */ {128, 512, 2048, 256, delta_deflate_slow},
/* 8 */ {256,2048, 4098, 1024, delta_deflate_slow},
/* 9 */ {256,4098, 4098, 4096, delta_deflate_slow}}; /* maximum compression */
/* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
* For deflate_fast() (levels <= 3) good is ignored and lazy has a different
* meaning.
*/
#define EQUAL 0
/* result of memcmp for equal strings */
/* zdelta: additional MACRO definitions */
#define ZD_DISTANCE(x,y) ((x)>(y)?(x)-(y):(y)-(x))
/* reference sliding window */
#define ZD_TIME_TO_CHECK 2
#define ZD_HIST_SIZE 1000
#define ZD_GET_NEXT_POS(ind)(++ind == ZD_HIST_SIZE?0:ind)
struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
/* zdelta: no changes in hash tables; completely reuse zlib code;
* add MACROs for the reference hash table
*/
/* ===========================================================================
* Update a hash value with the given input byte
* IN assertion: all calls to to UPDATE_HASH are made with consecutive
* input characters, so that a running hash key can be computed from the
* previous key instead of complete recalculation each time.
*/
#define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
/* ===========================================================================
* Insert string str in the dictionary and set match_head to the previous head
* of the hash chain (the most recent string with same hash key). Return
* the previous length of the hash chain.
* If this file is compiled with -DFASTEST, the compression level is forced
* to 1, and no hash chains are maintained.
* IN assertion: all calls to to INSERT_STRING are made with consecutive
* input characters and the first MIN_MATCH bytes of str are valid
* (except for the last MIN_MATCH-1 bytes of the input file).
*/
#ifdef FASTEST
#define INSERT_STRING(s, str, match_head) \
(UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
match_head = s->head[s->ins_h], \
s->head[s->ins_h] = (Pos)(str))
#else
#define INSERT_STRING(s, str, match_head) \
(UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
s->prev[(str) & s->w_mask] = match_head = s->head[s->ins_h], \
s->head[s->ins_h] = (Pos)(str))
#endif
/* zdelta: added */
#define INSERT_REF_STRING(s, str, rw) \
(UPDATE_HASH(s, s->ref_h, s->ref_window[rw][(str) + (MIN_MATCH-1)]), \
s->ref_prev[rw][((Pos) str) & s->rw_mask] = s->ref_head[rw][s->ref_h], \
s->ref_head[rw][s->ref_h] = (Pos)(str))
/* ===========================================================================
* Initialize the hash table (avoiding 64K overflow for 16 bit systems).
* prev[] will be initialized on the fly.
*/
#define CLEAR_HASH(s) \
s->head[s->hash_size-1] = NIL; \
zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
#define CLEAR_REF_HASH(s, rw) \
s->ref_head[rw][s->hash_size-1] = NIL; \
zmemzero((Bytef *)s->ref_head[rw], \
(unsigned)(s->hash_size-1)*sizeof(*s->ref_head[rw]));
/* ========================================================================= */
/* zdelta: modified
* added zd prefix to the name
*/
int ZEXPORT zd_deflateReset (strm)
zd_streamp strm;
{
deflate_state *s;
int rw;
if (strm == ZD_NULL || strm->state == ZD_NULL ||
strm->zalloc == ZD_NULL || strm->zfree == ZD_NULL ||
strm->refnum < 0 || strm->refnum > REFNUM) return ZD_STREAM_ERROR;
strm->total_in = strm->total_out = 0;
for(rw=0;rw<strm->refnum;++rw) strm->base_out[rw] = 0;
strm->msg = ZD_NULL; /* use zfree if we ever allocate msg dynamically */
strm->data_type = Z_UNKNOWN;
s = (deflate_state *)strm->state;
s->pending = 0;
s->pending_out = s->pending_buf;
if (s->noheader < 0) {
s->noheader = 0; /* was set to -1 by deflate(..., ZD_FINISH); */
}
s->status = s->noheader ? BUSY_STATE : INIT_STATE;
strm->adler = 1;
s->last_flush = Z_NO_FLUSH;
zd_tr_init(s);
lm_init(s);
/* zdelta: initialize the reference hash tables here
* the first ref_window_size bytes are inserted
* into the reference dictionary
*/
for(rw=0;rw<strm->refnum;++rw){
if(strm->base_avail[rw] >= MIN_MATCH) init_ref_window(s,rw);
}
/* zdelta: initialize the target hash table here;
* this will save us sliding an empty hash table!
* no insertions are done
*/
if (strm->avail_in >= MIN_MATCH)
init_window(s);
return ZD_OK;
}
/* ========================================================================= */
/* zdelta: modified
* added zd prefix to the name
*/
int ZEXPORT zd_deflateParams(strm, level, strategy)
zd_streamp strm;
int level;
int strategy;
{
deflate_state *s;
compress_func func;
int err = ZD_OK;
if (strm == ZD_NULL || strm->state == ZD_NULL ||
strm->refnum < 0 || strm->refnum > REFNUM) return ZD_STREAM_ERROR;
s = strm->state;
if (level == ZD_DEFAULT_COMPRESSION) {
level = 7;
}
if (level < 0 || level > 9 || strategy < 0 || strategy > 8) {
return ZD_STREAM_ERROR;
}
func = configuration_table[s->level].func;
if (func != configuration_table[level].func && strm->total_in != 0) {
/* Flush the last buffer: */
err = zd_deflate(strm, Z_PARTIAL_FLUSH);
}
if (s->level != level) {
s->level = level;
s->max_lazy_match = configuration_table[level].max_lazy;
s->good_match = configuration_table[level].good_length;
s->nice_match = configuration_table[level].nice_length;
s->max_chain_length = configuration_table[level].max_chain;
}
s->strategy = strategy;
return err;
}
/* ========================================================================= */
int ZEXPORT zd_deflateInit_(strm, level, version, stream_size)
zd_streamp strm;
int level;
const char *version;
int stream_size;
{
return zd_deflateInit2_(strm, level, ZD_DEFLATED, MAX_WBITS,
DEF_MEM_LEVEL, ZD_DEFAULT_STRATEGY, version,
stream_size);
/* To do: ignore strm->next_in if we use it as window */
}
/* ========================================================================= */
/* zdelta: modified
* added zd prefix to the name
*/
int ZEXPORT zd_deflateInit2_(strm, level, method, windowBits, memLevel,
strategy, version, stream_size)
zd_streamp strm;
int level;
int method;
int windowBits;
int memLevel;
int strategy;
const char *version;
int stream_size;
{
deflate_state *s;
int noheader = 0;
int refnum = strm->refnum;
static const char* zd_version = ZDLIB_VERSION;
int i;
ushf *overlay;
/* We overlay pending_buf and d_buf+l_buf. This works since the average
* output size for (length,distance) codes is <= 24 bits.
*/
if (version == ZD_NULL || version[0] != zd_version[0] ||
stream_size != sizeof(zd_stream)) {
return ZD_VERSION_ERROR;
}
if (strm == ZD_NULL) return ZD_STREAM_ERROR;
strm->msg = ZD_NULL;
if (strm->zalloc == ZD_NULL) {
strm->zalloc = zd_zcalloc;
strm->opaque = (voidpf)0;
}
if (strm->zfree == ZD_NULL) strm->zfree = zd_zcfree;
if (level == ZD_DEFAULT_COMPRESSION) level = 7;
#ifdef FASTEST
level = 1;
#endif
if (windowBits < 0) { /* undocumented feature: suppress zdlib header */
noheader = 1;
windowBits = -windowBits;
}
#ifdef NO_ERROR_CHECK /* suppress zdlib header at compile time */
noheader = 1;
#endif
if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != ZD_DEFLATED ||
windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
strategy < ZD_HUFFMAN_ONLY || strategy > 8 ||
refnum < 0 || refnum > REFNUM)
{
return ZD_STREAM_ERROR;
}
s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
if (s == ZD_NULL) return ZD_MEM_ERROR;
strm->state = (struct zd_internal_state FAR *)s;
s->strm = strm;
s->noheader = noheader;
s->w_bits = windowBits;
s->w_size = 1 << s->w_bits;
s->w_mask = s->w_size - 1;
s->hash_bits = memLevel + 7;
s->hash_size = 1 << s->hash_bits;
s->hash_mask = s->hash_size - 1;
s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
/* zdelta: reference window mask */
s->rw_mask = (s->w_size << 1) - 1;
/* zdelta: needed for the correctness of reference_longest_match() */
s->ref_window[0]=(Bytef *) ZALLOC(strm, s->w_size*2*(refnum+1),sizeof(Byte));
s->window =(Bytef *) (s->ref_window[0]+(2*refnum*s->w_size));
s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
/* zdelta: reference data hash table */
s->ref_prev[0] = (Posf *) ZALLOC(strm, s->w_size*(2*refnum), sizeof(Pos));
s->ref_head[0] = (Posf *) ZALLOC(strm, s->hash_size*(refnum), sizeof(Pos));
s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, 2*sizeof(ush)+2);
s->pending_buf = (uchf *) overlay;
s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
if (s->ref_window[0] == ZD_NULL || s->prev == ZD_NULL ||
s->head == ZD_NULL || s->ref_prev[0] == ZD_NULL ||
s->ref_head[0] == ZD_NULL || s->pending_buf == ZD_NULL)
{
strm->msg = (char*)ERR_MSG(ZD_MEM_ERROR);
zd_deflateEnd (strm);
return ZD_MEM_ERROR;
}
s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
s->l_buf = s->d_buf + s->lit_bufsize;
s->z_buf = s->pending_buf + (1+2*sizeof(ush))*s->lit_bufsize;
/* zdelta: initialize reference window buffers */
for(i=1;i<refnum;++i){
s->ref_window[i] = (Bytef *) (s->ref_window[0] +(s->w_size)*2*i);
s->ref_prev[i] = (Posf *) (s->ref_prev[0] + (s->w_size)*2*i);
s->ref_head[i] = (Posf *) (s->ref_head[0] + i*(s->hash_size));
}
/* zdelta: these variables are not used; kept for future use */
s->level = level;
s->strategy = strategy;
s->method = (Byte)method;
if(zd_deflateReset(strm)!=ZD_OK){
return ZD_STREAM_ERROR;
};
return ZD_OK;
}
/* =========================================================================
* Put a short in the pending buffer. The 16-bit value is put in MSB order.
* IN assertion: the stream state is correct and there is enough room in
* pending_buf.
*/
local void putShortMSB (s, b)
deflate_state *s;
uInt b;
{
put_byte(s, (Byte)(b >> 8));
put_byte(s, (Byte)(b & 0xff));
}
/* =========================================================================
* Flush as much pending output as possible. All deflate() output goes
* through this function so some applications may wish to modify it
* to avoid allocating a large strm->next_out buffer and copying into it.
* (See also read_buf()).
*/
local void flush_pending(strm)
zd_streamp strm;
{
unsigned len = strm->state->pending;
if (len > strm->avail_out) len = strm->avail_out;
if (len == 0) return;
zmemcpy(strm->next_out, strm->state->pending_out, len);
strm->next_out += len;
strm->state->pending_out += len;
strm->total_out += len;
strm->avail_out -= len;
strm->state->pending -= len;
if (strm->state->pending == 0) {
strm->state->pending_out = strm->state->pending_buf;
}
}
/* ========================================================================= */
/* zdelta: modified
* added prefix zd to the name
* no code for preset dictionaries
*/
int ZEXPORT zd_deflate (strm, flush)
zd_streamp strm;
int flush;
{
int old_flush; /* value of flush param for previous deflate call */
deflate_state *s;
if (strm == ZD_NULL || strm->state == ZD_NULL ||
flush > ZD_FINISH || flush < 0) {
return ZD_STREAM_ERROR;
}
s = strm->state;
if (strm->next_out == ZD_NULL ||
(strm->next_in == ZD_NULL && strm->avail_in != 0) ||
(s->status == FINISH_STATE && flush != ZD_FINISH) ||
strm->refnum<0 || strm->refnum>REFNUM) {
ERR_RETURN(strm, ZD_STREAM_ERROR);
}
if (strm->avail_out == 0) ERR_RETURN(strm, ZD_BUF_ERROR);
s->strm = strm; /* just in case */
old_flush = s->last_flush;
s->last_flush = flush;
/* Write the libzd header */
if (s->status == INIT_STATE) {
uInt header = (ZD_DEFLATED + ((s->w_bits-8)<<4)) << 8;
uInt level_flags = (s->level-1) >> 1;
if (level_flags > 3) level_flags = 3;
header |= (level_flags << 6);
header += 31 - (header % 31);
s->status = BUSY_STATE;
putShortMSB(s, header);
}
/* Flush as much pending output as possible */
if (s->pending != 0) {
flush_pending(strm);
if (strm->avail_out == 0) {
/* Since avail_out is 0, deflate will be called again with
* more output space, but possibly with both pending and
* avail_in equal to zero. There won't be anything to do,
* but this is not an error situation so make sure we
* return OK instead of BUF_ERROR at next call of deflate:
*/
s->last_flush = -1;
return ZD_OK;
}
/* Make sure there is something to do and avoid duplicate consecutive
* flushes. For repeated and useless calls with ZD_FINISH, we keep
* returning ZD_STREAM_END instead of ZD_BUFF_ERROR.
*/
} else if (strm->avail_in == 0 && flush <= old_flush &&
flush != ZD_FINISH) {
ERR_RETURN(strm, ZD_BUF_ERROR);
}
/* User must not provide more input after the first FINISH: */
if (s->status == FINISH_STATE && strm->avail_in != 0) {
ERR_RETURN(strm, ZD_BUF_ERROR);
}
/* Start a new block or continue the current one.
*/
if (strm->avail_in != 0 || s->lookahead != 0 ||
(flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
block_state bstate;
/* zdelta: currently only one level of compression */
bstate = (*(configuration_table[s->level].func))(s, flush);
if (bstate == finish_started || bstate == finish_done) {
s->status = FINISH_STATE;
}
if (bstate == need_more || bstate == finish_started) {
if (strm->avail_out == 0) {
s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
}
return ZD_OK;
/* If flush != Z_NO_FLUSH && avail_out == 0, the next call
* of deflate should use the same flush parameter to make sure
* that the flush is complete. So we don't have to output an
* empty block here, this will be done at next call. This also
* ensures that for a very small output buffer, we emit at most
* one empty block.
*/
}
if (bstate == block_done) {
if (flush == Z_PARTIAL_FLUSH) {
zd_tr_align(s);
} else { /* FULL_FLUSH or SYNC_FLUSH */
zd_tr_stored_block(s, (char*)0, 0L, 0);
/* For a full flush, this empty block will be recognized
* as a special marker by inflate_sync().
*/
if (flush == ZD_FULL_FLUSH) {
CLEAR_HASH(s); /* forget history */
}
}
flush_pending(strm);
if (strm->avail_out == 0) {
s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
return ZD_OK;
}
}
}
Assert(strm->avail_out > 0, "bug2");
if (flush != ZD_FINISH) return ZD_OK;
if (s->noheader) return ZD_STREAM_END;
/* Write the libzd trailer (adler32) */
putShortMSB(s, (uInt)(strm->adler >> 16));
putShortMSB(s, (uInt)(strm->adler & 0xffff));
flush_pending(strm);
/* If avail_out is zero, the application will call deflate again
* to flush the rest.
*/
s->noheader = -1; /* write the trailer only once! */
return s->pending != 0 ? ZD_OK : ZD_STREAM_END;
}
/* ========================================================================= */
/* zdelta: modified
* added prefix zd to the name
* modified to handle multiple reference files
*/
int ZEXPORT zd_deflateEnd (strm)
zd_streamp strm;
{
int status;
if (strm == ZD_NULL || strm->state == ZD_NULL) return ZD_STREAM_ERROR;
status = strm->state->status;
if (status != INIT_STATE && status != BUSY_STATE &&
status != FINISH_STATE) {
return ZD_STREAM_ERROR;
}
/* Deallocate in reverse order of allocations: */
/* zdelta: deallocate zdelta buffers */
TRY_FREE(strm, strm->state->pending_buf);
TRY_FREE(strm, strm->state->ref_head[0]);
TRY_FREE(strm, strm->state->ref_prev[0]);
TRY_FREE(strm, strm->state->head);
TRY_FREE(strm, strm->state->prev);
/* zdelta: strm->state->window now points at the middle of
* strm->state->ref_window
*/
TRY_FREE(strm, strm->state->ref_window[0]);
ZFREE(strm, strm->state);
strm->state = ZD_NULL;
return status == BUSY_STATE ? ZD_DATA_ERROR : ZD_OK;
}
/* ===========================================================================
* Read a new buffer from the current input stream, update the adler32
* and total number of bytes read. All deflate() input goes through
* this function so some applications may wish to modify it to avoid
* allocating a large strm->next_in buffer and copying from it.
* (See also flush_pending()).
*/
local int read_buf(strm, buf, size)
zd_streamp strm;
Bytef *buf;
unsigned size;
{
unsigned len = strm->avail_in;
if (len > size) len = size;
if (len == 0) return 0;
strm->avail_in -= len;
if (!strm->state->noheader) {
strm->adler = zd_adler32(strm->adler, strm->next_in, len);
}
zmemcpy(buf, strm->next_in, len);
strm->next_in += len;
strm->total_in += len;
return (int)len;
}
/* ===========================================================================
* zdelta:added
* Read new data from the reference input stream;
* updates the total number of bytes read.
*/
local int read_ref_buf(strm, buf, size, rw)
zd_streamp strm;
Bytef *buf;
unsigned size;
int rw;
{
unsigned len = strm->base_avail[rw];
if (len > size) len = size;
if (len == 0) return 0;
strm->base_avail[rw] -= len;
zmemcpy(buf, strm->base[rw], len);
strm->base[rw] += len;
strm->base_out[rw] += len;
return (int)len;
}
/* ===========================================================================
* zdelta:modified
* only one compression level
* Initialize the "longest match" routines for a new zlib stream
*/
local void lm_init (s)
deflate_state *s;
{
int i;
int refnum = s->strm->refnum;
s->window_size = (ulg)2L*s->w_size;
/*s->ref_window_size = (ulg)2L*s->w_size;*/
s->strstart = 0;
s->block_start = 0L;
s->lookahead = 0;
s->match_length = s->prev_length = MIN_MATCH-1;
s->match_available = 0;
s->ins_h = 0;
s->match_benefit = s->prev_benefit = 0;
/* Set the default configuration parameters:
*/
s->max_lazy_match = configuration_table[s->level].max_lazy;
s->good_match = configuration_table[s->level].good_length;
s->max_chain_length = configuration_table[s->level].max_chain;
s->nice_match = configuration_table[s->level].nice_length;
/* zdelta: initialize reference data pointers */
for(i=0; i<refnum*ZD_RPN; ++i){
s->rwptr[i] = s->rwptr_save[i] = 0;
s->stable[i] = s->stable_save[i] = 0;
}
for(i=0; i<refnum; ++i){
s->stored_allowed[i] = 1;
s->ref_window_size[i] = (ulg)2L*s->w_size;
}
}
/* ===========================================================================
* Fill the window when the lookahead becomes insufficient.
* Updates strstart and lookahead.
*
* IN assertion: lookahead < MIN_LOOKAHEAD
* OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
* At least one byte has been read, or avail_in == 0; reads are
* performed for at least two bytes (required for the zip translate_eol
* option -- not supported here).
*/
local void
fill_window(s)
deflate_state *s;
{
register unsigned n, m;
register Posf *p;
unsigned more; /* Amount of free space at the end of the window. */
uInt wsize = s->w_size;
do {
more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
/* Deal with !@#$% 64K limit: */
if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
more = wsize;
} else if (more == (unsigned)(-1)) {
/* Very unlikely, but possible on 16 bit machine if strstart == 0
* and lookahead == 1 (input done one byte at time)
*/
more--;
/* If the window is almost full and there is insufficient lookahead,
* move the upper half to the lower one to make room in the upper half.
*/
} else if (s->strstart >= wsize+MAX_DIST(s)) {
zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
/* the match may be in the refference window; dont change it always */
if(s->match_ptr == ZD_TARP) s->match_start -= wsize;
s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
s->block_start -= (long) wsize;
/* Slide the hash table (could be avoided with 32 bit values
at the expense of memory usage). We slide even when level == 0
to keep the hash table consistent if we switch back to level > 0
later. (Using level 0 permanently is not an optimal usage of
zlib, so we don't care about this pathological case.)
*/
n = s->hash_size;
p = &s->head[n];
do {
m = *--p;
*p = (Pos)(m >= wsize ? m-wsize : NIL);
} while (--n);
n = wsize;
#ifndef FASTEST
p = &s->prev[n];
do {
m = *--p;
*p = (Pos)(m >= wsize ? m-wsize : NIL);
/* If n is not on any hash chain, prev[n] is garbage but
* its value will never be used.
*/
} while (--n);
#endif
more += wsize;
}
if (s->strm->avail_in == 0) return;
/* If there was no sliding:
* strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
* more == window_size - lookahead - strstart
* => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
* => more >= window_size - 2*WSIZE + 2
* In the BIG_MEM or MMAP case (not yet supported),
* window_size == input_size + MIN_LOOKAHEAD &&
* strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
* Otherwise, window_size == 2*WSIZE so more >= 2.
* If there was sliding, more >= WSIZE. So in all cases, more >= 2.
*/
Assert(more >= 2, "more < 2");
n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
s->lookahead += n;
/* Initialize the hash value now that we have some input: */
if (s->lookahead >= MIN_MATCH) {
s->ins_h = s->window[s->strstart];
UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
#if MIN_MATCH != 3
Call UPDATE_HASH() MIN_MATCH-3 more times
#endif
}
/* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
* but this is not important since only literal bytes will be emitted.
*/
} while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
}
/* ===========================================================================
* zdelta: added
* fill reference window when too many matches are found at the end
* of the current reference buffer (see delta_deflate for more details)
*
* OUT assertions:
* At least one byte has been read, or base_avail == 0;
*/
local void
fill_ref_window(s, rw)
deflate_state *s;
int rw;
{
uInt i;
uInt wsize = s->w_size;
uInt nb;
/* zdelta: slide the window always by wsize */
zmemcpy((Bytef*) s->ref_window[rw],
(Bytef*) (s->ref_window[rw]+wsize),
(unsigned)wsize*sizeof(Bytef));
nb = read_ref_buf(s->strm,s->ref_window[rw]+wsize, wsize, rw);
/* zdelta: set the real ref_window_size */
s->ref_window_size[rw] = wsize+nb;
/* zdelta: update reference window pointers */
/* if a given pointer is too far from the window,
* it will never be used again; stop updating it
* TODO: needs better solution for this
*/
if(s->rwptr[2*rw] > (- ZD_UNREACHABLE)) s->rwptr[2*rw] -=wsize;
if(s->rwptr[2*rw+1]> (- ZD_UNREACHABLE)) s->rwptr[2*rw+1] -=wsize;
/* zdelta: flush reference dictionary */
CLEAR_REF_HASH(s, rw);
s->ref_h = s->ref_window[rw][0];
/* zdelta: and rebuild the dictionary from the beginning
* same speed if slided as the target trailing window
* better compression since no hashes are lost
*/
UPDATE_HASH(s, s->ref_h, s->ref_window[rw][1]);
for(i = 0;i <= s->ref_window_size[rw] - MIN_MATCH; i++){
INSERT_REF_STRING(s,i,rw);
}
s->stored_allowed[rw] = 0;
}
/* zdelta:added
* called only once at the beginnig of deflatation
*/
local void
init_ref_window(s, rw)
deflate_state *s;
int rw;
{
uInt i;
uInt n;
n = read_ref_buf(s->strm, s->ref_window[rw], s->ref_window_size[rw], rw);
s->ref_window_size[rw] = n;
/* clear memory */
CLEAR_REF_HASH(s,rw);
s->ref_h = s->ref_window[rw][0];
UPDATE_HASH(s, s->ref_h, s->ref_window[rw][1]);
for(i = 0;i <= n - MIN_MATCH ;i++){
INSERT_REF_STRING(s, i, rw);
}
}
/* ===========================================================================
* zdelta:added
* Initialize the target data window
* This will save us the overhead of updating an empty hash table at the
* first call of deflate
* Updates lookahead and ins_h.
*
* IN assertion: called before the first execution of deflate()
* OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
* At least one byte has been read, or avail_in == 0;
*/
local void
init_window(s)
deflate_state *s;
{
s->lookahead = read_buf(s->strm, s->window, (unsigned) s->window_size);
/* zdelta: Initialize the hash value now that we have some input: */
if (s->lookahead >= MIN_MATCH) {
s->ins_h = s->window[s->strstart];
UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
#if MIN_MATCH != 3
Call UPDATE_HASH() MIN_MATCH-3 more times
#endif
}
/* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
* but this is not important since only literal bytes will be emitted.
*/
}
/* ===========================================================================
* Flush the current block, with given end-of-file flag.
* IN assertion: strstart is set to the end of the current match.
*
* zdelta: added zd prefix to the _tr_flush_block
*/
#define FLUSH_BLOCK_ONLY(s, eof) { \
zd_tr_flush_block(s, (s->block_start >= 0L ? \
(charf *)&s->window[(unsigned)s->block_start] : \