Subversion-Projekte lars-tiefland.cienc

Revision

Details | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
9 lars 1
/*
2
 Copyright (c) 2013 Gildas Lormeau. All rights reserved.
3
 
4
 Redistribution and use in source and binary forms, with or without
5
 modification, are permitted provided that the following conditions are met:
6
 
7
 1. Redistributions of source code must retain the above copyright notice,
8
 this list of conditions and the following disclaimer.
9
 
10
 2. Redistributions in binary form must reproduce the above copyright
11
 notice, this list of conditions and the following disclaimer in
12
 the documentation and/or other materials provided with the distribution.
13
 
14
 3. The names of the authors may not be used to endorse or promote products
15
 derived from this software without specific prior written permission.
16
 
17
 THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
18
 INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
19
 FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
20
 INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
21
 INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22
 LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
23
 OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
24
 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
25
 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
26
 EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
 */
28
 
29
/*
30
 * This program is based on JZlib 1.0.2 ymnk, JCraft,Inc.
31
 * JZlib is based on zlib-1.1.3, so all credit should go authors
32
 * Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
33
 * and contributors of zlib.
34
 */
35
 
36
// Global
37
 
38
var MAX_BITS = 15;
39
var D_CODES = 30;
40
var BL_CODES = 19;
41
 
42
var LENGTH_CODES = 29;
43
var LITERALS = 256;
44
var L_CODES = (LITERALS + 1 + LENGTH_CODES);
45
var HEAP_SIZE = (2 * L_CODES + 1);
46
 
47
var END_BLOCK = 256;
48
 
49
// Bit length codes must not exceed MAX_BL_BITS bits
50
var MAX_BL_BITS = 7;
51
 
52
// repeat previous bit length 3-6 times (2 bits of repeat count)
53
var REP_3_6 = 16;
54
 
55
// repeat a zero length 3-10 times (3 bits of repeat count)
56
var REPZ_3_10 = 17;
57
 
58
// repeat a zero length 11-138 times (7 bits of repeat count)
59
var REPZ_11_138 = 18;
60
 
61
// The lengths of the bit length codes are sent in order of decreasing
62
// probability, to avoid transmitting the lengths for unused bit
63
// length codes.
64
 
65
var Buf_size = 8 * 2;
66
 
67
// JZlib version : "1.0.2"
68
var Z_DEFAULT_COMPRESSION = -1;
69
 
70
// compression strategy
71
var Z_FILTERED = 1;
72
var Z_HUFFMAN_ONLY = 2;
73
var Z_DEFAULT_STRATEGY = 0;
74
 
75
var Z_NO_FLUSH = 0;
76
var Z_PARTIAL_FLUSH = 1;
77
var Z_FULL_FLUSH = 3;
78
var Z_FINISH = 4;
79
 
80
var Z_OK = 0;
81
var Z_STREAM_END = 1;
82
var Z_NEED_DICT = 2;
83
var Z_STREAM_ERROR = -2;
84
var Z_DATA_ERROR = -3;
85
var Z_BUF_ERROR = -5;
86
 
87
// Tree
88
 
89
// see definition of array dist_code below
90
var _dist_code = [ 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
91
        10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
92
        12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
93
        13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
94
        14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
95
        14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
96
        15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17, 18, 18, 19, 19,
97
        20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
98
        24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
99
        26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
100
        27, 27, 27, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
101
        28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 29,
102
        29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
103
        29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29 ];
104
 
105
function Tree() {
106
    'use strict';
107
    var that = this;
108
 
109
    // dyn_tree; // the dynamic tree
110
    // max_code; // largest code with non zero frequency
111
    // stat_desc; // the corresponding static tree
112
 
113
    // Compute the optimal bit lengths for a tree and update the total bit
114
    // length
115
    // for the current block.
116
    // IN assertion: the fields freq and dad are set, heap[heap_max] and
117
    // above are the tree nodes sorted by increasing frequency.
118
    // OUT assertions: the field len is set to the optimal bit length, the
119
    // array bl_count contains the frequencies for each bit length.
120
    // The length opt_len is updated; static_len is also updated if stree is
121
    // not null.
122
    function gen_bitlen(s) {
123
        var tree = that.dyn_tree;
124
        var stree = that.stat_desc.static_tree;
125
        var extra = that.stat_desc.extra_bits;
126
        var base = that.stat_desc.extra_base;
127
        var max_length = that.stat_desc.max_length;
128
        var h; // heap index
129
        var n, m; // iterate over the tree elements
130
        var bits; // bit length
131
        var xbits; // extra bits
132
        var f; // frequency
133
        var overflow = 0; // number of elements with bit length too large
134
 
135
        for (bits = 0; bits <= MAX_BITS; bits++)
136
            s.bl_count[bits] = 0;
137
 
138
        // In a first pass, compute the optimal bit lengths (which may
139
        // overflow in the case of the bit length tree).
140
        tree[s.heap[s.heap_max] * 2 + 1] = 0; // root of the heap
141
 
142
        for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {
143
            n = s.heap[h];
144
            bits = tree[tree[n * 2 + 1] * 2 + 1] + 1;
145
            if (bits > max_length) {
146
                bits = max_length;
147
                overflow++;
148
            }
149
            tree[n * 2 + 1] = bits;
150
            // We overwrite tree[n*2+1] which is no longer needed
151
 
152
            if (n > that.max_code)
153
                continue; // not a leaf node
154
 
155
            s.bl_count[bits]++;
156
            xbits = 0;
157
            if (n >= base)
158
                xbits = extra[n - base];
159
            f = tree[n * 2];
160
            s.opt_len += f * (bits + xbits);
161
            if (stree)
162
                s.static_len += f * (stree[n * 2 + 1] + xbits);
163
        }
164
        if (overflow === 0)
165
            return;
166
 
167
        // This happens for example on obj2 and pic of the Calgary corpus
168
        // Find the first bit length which could increase:
169
        do {
170
            bits = max_length - 1;
171
            while (s.bl_count[bits] === 0)
172
                bits--;
173
            s.bl_count[bits]--; // move one leaf down the tree
174
            s.bl_count[bits + 1] += 2; // move one overflow item as its brother
175
            s.bl_count[max_length]--;
176
            // The brother of the overflow item also moves one step up,
177
            // but this does not affect bl_count[max_length]
178
            overflow -= 2;
179
        } while (overflow > 0);
180
 
181
        for (bits = max_length; bits !== 0; bits--) {
182
            n = s.bl_count[bits];
183
            while (n !== 0) {
184
                m = s.heap[--h];
185
                if (m > that.max_code)
186
                    continue;
187
                if (tree[m * 2 + 1] != bits) {
188
                    s.opt_len += (bits - tree[m * 2 + 1]) * tree[m * 2];
189
                    tree[m * 2 + 1] = bits;
190
                }
191
                n--;
192
            }
193
        }
194
    }
195
 
196
    // Reverse the first len bits of a code, using straightforward code (a
197
    // faster
198
    // method would use a table)
199
    // IN assertion: 1 <= len <= 15
200
    function bi_reverse(code, // the value to invert
201
    len // its bit length
202
    ) {
203
        var res = 0;
204
        do {
205
            res |= code & 1;
206
            code >>>= 1;
207
            res <<= 1;
208
        } while (--len > 0);
209
        return res >>> 1;
210
    }
211
 
212
    // Generate the codes for a given tree and bit counts (which need not be
213
    // optimal).
214
    // IN assertion: the array bl_count contains the bit length statistics for
215
    // the given tree and the field len is set for all tree elements.
216
    // OUT assertion: the field code is set for all tree elements of non
217
    // zero code length.
218
    function gen_codes(tree, // the tree to decorate
219
    max_code, // largest code with non zero frequency
220
    bl_count // number of codes at each bit length
221
    ) {
222
        var next_code = []; // next code value for each
223
        // bit length
224
        var code = 0; // running code value
225
        var bits; // bit index
226
        var n; // code index
227
        var len;
228
 
229
        // The distribution counts are first used to generate the code values
230
        // without bit reversal.
231
        for (bits = 1; bits <= MAX_BITS; bits++) {
232
            next_code[bits] = code = ((code + bl_count[bits - 1]) << 1);
233
        }
234
 
235
        // Check that the bit counts in bl_count are consistent. The last code
236
        // must be all ones.
237
        // Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
238
        // "inconsistent bit counts");
239
        // Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
240
 
241
        for (n = 0; n <= max_code; n++) {
242
            len = tree[n * 2 + 1];
243
            if (len === 0)
244
                continue;
245
            // Now reverse the bits
246
            tree[n * 2] = bi_reverse(next_code[len]++, len);
247
        }
248
    }
249
 
250
    // Construct one Huffman tree and assigns the code bit strings and lengths.
251
    // Update the total bit length for the current block.
252
    // IN assertion: the field freq is set for all tree elements.
253
    // OUT assertions: the fields len and code are set to the optimal bit length
254
    // and corresponding code. The length opt_len is updated; static_len is
255
    // also updated if stree is not null. The field max_code is set.
256
    that.build_tree = function(s) {
257
        var tree = that.dyn_tree;
258
        var stree = that.stat_desc.static_tree;
259
        var elems = that.stat_desc.elems;
260
        var n, m; // iterate over heap elements
261
        var max_code = -1; // largest code with non zero frequency
262
        var node; // new node being created
263
 
264
        // Construct the initial heap, with least frequent element in
265
        // heap[1]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
266
        // heap[0] is not used.
267
        s.heap_len = 0;
268
        s.heap_max = HEAP_SIZE;
269
 
270
        for (n = 0; n < elems; n++) {
271
            if (tree[n * 2] !== 0) {
272
                s.heap[++s.heap_len] = max_code = n;
273
                s.depth[n] = 0;
274
            } else {
275
                tree[n * 2 + 1] = 0;
276
            }
277
        }
278
 
279
        // The pkzip format requires that at least one distance code exists,
280
        // and that at least one bit should be sent even if there is only one
281
        // possible code. So to avoid special checks later on we force at least
282
        // two codes of non zero frequency.
283
        while (s.heap_len < 2) {
284
            node = s.heap[++s.heap_len] = max_code < 2 ? ++max_code : 0;
285
            tree[node * 2] = 1;
286
            s.depth[node] = 0;
287
            s.opt_len--;
288
            if (stree)
289
                s.static_len -= stree[node * 2 + 1];
290
            // node is 0 or 1 so it does not have extra bits
291
        }
292
        that.max_code = max_code;
293
 
294
        // The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
295
        // establish sub-heaps of increasing lengths:
296
 
297
        for (n = Math.floor(s.heap_len / 2); n >= 1; n--)
298
            s.pqdownheap(tree, n);
299
 
300
        // Construct the Huffman tree by repeatedly combining the least two
301
        // frequent nodes.
302
 
303
        node = elems; // next internal node of the tree
304
        do {
305
            // n = node of least frequency
306
            n = s.heap[1];
307
            s.heap[1] = s.heap[s.heap_len--];
308
            s.pqdownheap(tree, 1);
309
            m = s.heap[1]; // m = node of next least frequency
310
 
311
            s.heap[--s.heap_max] = n; // keep the nodes sorted by frequency
312
            s.heap[--s.heap_max] = m;
313
 
314
            // Create a new node father of n and m
315
            tree[node * 2] = (tree[n * 2] + tree[m * 2]);
316
            s.depth[node] = Math.max(s.depth[n], s.depth[m]) + 1;
317
            tree[n * 2 + 1] = tree[m * 2 + 1] = node;
318
 
319
            // and insert the new node in the heap
320
            s.heap[1] = node++;
321
            s.pqdownheap(tree, 1);
322
        } while (s.heap_len >= 2);
323
 
324
        s.heap[--s.heap_max] = s.heap[1];
325
 
326
        // At this point, the fields freq and dad are set. We can now
327
        // generate the bit lengths.
328
 
329
        gen_bitlen(s);
330
 
331
        // The field len is now set, we can generate the bit codes
332
        gen_codes(tree, that.max_code, s.bl_count);
333
    };
334
 
335
}
336
 
337
Tree._length_code = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16,
338
        16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20,
339
        20, 20, 20, 20, 20, 20, 20, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
340
        22, 22, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
341
        24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
342
        25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
343
        26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28 ];
344
 
345
Tree.base_length = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 0 ];
346
 
347
Tree.base_dist = [ 0, 1, 2, 3, 4, 6, 8, 12, 16, 24, 32, 48, 64, 96, 128, 192, 256, 384, 512, 768, 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384,
348
        24576 ];
349
 
350
// Mapping from a distance to a distance code. dist is the distance - 1 and
351
// must not have side effects. _dist_code[256] and _dist_code[257] are never
352
// used.
353
Tree.d_code = function(dist) {
354
    return ((dist) < 256 ? _dist_code[dist] : _dist_code[256 + ((dist) >>> 7)]);
355
};
356
 
357
// extra bits for each length code
358
Tree.extra_lbits = [ 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0 ];
359
 
360
// extra bits for each distance code
361
Tree.extra_dbits = [ 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13 ];
362
 
363
// extra bits for each bit length code
364
Tree.extra_blbits = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7 ];
365
 
366
Tree.bl_order = [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];
367
 
368
// StaticTree
369
 
370
function StaticTree(static_tree, extra_bits, extra_base, elems, max_length) {
371
    var that = this;
372
    that.static_tree = static_tree;
373
    that.extra_bits = extra_bits;
374
    that.extra_base = extra_base;
375
    that.elems = elems;
376
    that.max_length = max_length;
377
}
378
 
379
StaticTree.static_ltree = [ 12, 8, 140, 8, 76, 8, 204, 8, 44, 8, 172, 8, 108, 8, 236, 8, 28, 8, 156, 8, 92, 8, 220, 8, 60, 8, 188, 8, 124, 8, 252, 8, 2, 8,
380
        130, 8, 66, 8, 194, 8, 34, 8, 162, 8, 98, 8, 226, 8, 18, 8, 146, 8, 82, 8, 210, 8, 50, 8, 178, 8, 114, 8, 242, 8, 10, 8, 138, 8, 74, 8, 202, 8, 42,
381
        8, 170, 8, 106, 8, 234, 8, 26, 8, 154, 8, 90, 8, 218, 8, 58, 8, 186, 8, 122, 8, 250, 8, 6, 8, 134, 8, 70, 8, 198, 8, 38, 8, 166, 8, 102, 8, 230, 8,
382
        22, 8, 150, 8, 86, 8, 214, 8, 54, 8, 182, 8, 118, 8, 246, 8, 14, 8, 142, 8, 78, 8, 206, 8, 46, 8, 174, 8, 110, 8, 238, 8, 30, 8, 158, 8, 94, 8,
383
        222, 8, 62, 8, 190, 8, 126, 8, 254, 8, 1, 8, 129, 8, 65, 8, 193, 8, 33, 8, 161, 8, 97, 8, 225, 8, 17, 8, 145, 8, 81, 8, 209, 8, 49, 8, 177, 8, 113,
384
        8, 241, 8, 9, 8, 137, 8, 73, 8, 201, 8, 41, 8, 169, 8, 105, 8, 233, 8, 25, 8, 153, 8, 89, 8, 217, 8, 57, 8, 185, 8, 121, 8, 249, 8, 5, 8, 133, 8,
385
        69, 8, 197, 8, 37, 8, 165, 8, 101, 8, 229, 8, 21, 8, 149, 8, 85, 8, 213, 8, 53, 8, 181, 8, 117, 8, 245, 8, 13, 8, 141, 8, 77, 8, 205, 8, 45, 8,
386
        173, 8, 109, 8, 237, 8, 29, 8, 157, 8, 93, 8, 221, 8, 61, 8, 189, 8, 125, 8, 253, 8, 19, 9, 275, 9, 147, 9, 403, 9, 83, 9, 339, 9, 211, 9, 467, 9,
387
        51, 9, 307, 9, 179, 9, 435, 9, 115, 9, 371, 9, 243, 9, 499, 9, 11, 9, 267, 9, 139, 9, 395, 9, 75, 9, 331, 9, 203, 9, 459, 9, 43, 9, 299, 9, 171, 9,
388
        427, 9, 107, 9, 363, 9, 235, 9, 491, 9, 27, 9, 283, 9, 155, 9, 411, 9, 91, 9, 347, 9, 219, 9, 475, 9, 59, 9, 315, 9, 187, 9, 443, 9, 123, 9, 379,
389
        9, 251, 9, 507, 9, 7, 9, 263, 9, 135, 9, 391, 9, 71, 9, 327, 9, 199, 9, 455, 9, 39, 9, 295, 9, 167, 9, 423, 9, 103, 9, 359, 9, 231, 9, 487, 9, 23,
390
        9, 279, 9, 151, 9, 407, 9, 87, 9, 343, 9, 215, 9, 471, 9, 55, 9, 311, 9, 183, 9, 439, 9, 119, 9, 375, 9, 247, 9, 503, 9, 15, 9, 271, 9, 143, 9,
391
        399, 9, 79, 9, 335, 9, 207, 9, 463, 9, 47, 9, 303, 9, 175, 9, 431, 9, 111, 9, 367, 9, 239, 9, 495, 9, 31, 9, 287, 9, 159, 9, 415, 9, 95, 9, 351, 9,
392
        223, 9, 479, 9, 63, 9, 319, 9, 191, 9, 447, 9, 127, 9, 383, 9, 255, 9, 511, 9, 0, 7, 64, 7, 32, 7, 96, 7, 16, 7, 80, 7, 48, 7, 112, 7, 8, 7, 72, 7,
393
        40, 7, 104, 7, 24, 7, 88, 7, 56, 7, 120, 7, 4, 7, 68, 7, 36, 7, 100, 7, 20, 7, 84, 7, 52, 7, 116, 7, 3, 8, 131, 8, 67, 8, 195, 8, 35, 8, 163, 8,
394
        99, 8, 227, 8 ];
395
 
396
StaticTree.static_dtree = [ 0, 5, 16, 5, 8, 5, 24, 5, 4, 5, 20, 5, 12, 5, 28, 5, 2, 5, 18, 5, 10, 5, 26, 5, 6, 5, 22, 5, 14, 5, 30, 5, 1, 5, 17, 5, 9, 5,
397
        25, 5, 5, 5, 21, 5, 13, 5, 29, 5, 3, 5, 19, 5, 11, 5, 27, 5, 7, 5, 23, 5 ];
398
 
399
StaticTree.static_l_desc = new StaticTree(StaticTree.static_ltree, Tree.extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);
400
 
401
StaticTree.static_d_desc = new StaticTree(StaticTree.static_dtree, Tree.extra_dbits, 0, D_CODES, MAX_BITS);
402
 
403
StaticTree.static_bl_desc = new StaticTree(null, Tree.extra_blbits, 0, BL_CODES, MAX_BL_BITS);
404
 
405
// Deflate
406
 
407
var MAX_MEM_LEVEL = 9;
408
var DEF_MEM_LEVEL = 8;
409
 
410
function Config(good_length, max_lazy, nice_length, max_chain, func) {
411
    var that = this;
412
    that.good_length = good_length;
413
    that.max_lazy = max_lazy;
414
    that.nice_length = nice_length;
415
    that.max_chain = max_chain;
416
    that.func = func;
417
}
418
 
419
var STORED = 0;
420
var FAST = 1;
421
var SLOW = 2;
422
var config_table = [ new Config(0, 0, 0, 0, STORED), new Config(4, 4, 8, 4, FAST), new Config(4, 5, 16, 8, FAST), new Config(4, 6, 32, 32, FAST),
423
        new Config(4, 4, 16, 16, SLOW), new Config(8, 16, 32, 32, SLOW), new Config(8, 16, 128, 128, SLOW), new Config(8, 32, 128, 256, SLOW),
424
        new Config(32, 128, 258, 1024, SLOW), new Config(32, 258, 258, 4096, SLOW) ];
425
 
426
var z_errmsg = [ "need dictionary", // Z_NEED_DICT
427
// 2
428
"stream end", // Z_STREAM_END 1
429
"", // Z_OK 0
430
"", // Z_ERRNO (-1)
431
"stream error", // Z_STREAM_ERROR (-2)
432
"data error", // Z_DATA_ERROR (-3)
433
"", // Z_MEM_ERROR (-4)
434
"buffer error", // Z_BUF_ERROR (-5)
435
"",// Z_VERSION_ERROR (-6)
436
"" ];
437
 
438
// block not completed, need more input or more output
439
var NeedMore = 0;
440
 
441
// block flush performed
442
var BlockDone = 1;
443
 
444
// finish started, need only more output at next deflate
445
var FinishStarted = 2;
446
 
447
// finish done, accept no more input or output
448
var FinishDone = 3;
449
 
450
// preset dictionary flag in zlib header
451
var PRESET_DICT = 0x20;
452
 
453
var INIT_STATE = 42;
454
var BUSY_STATE = 113;
455
var FINISH_STATE = 666;
456
 
457
// The deflate compression method
458
var Z_DEFLATED = 8;
459
 
460
var STORED_BLOCK = 0;
461
var STATIC_TREES = 1;
462
var DYN_TREES = 2;
463
 
464
var MIN_MATCH = 3;
465
var MAX_MATCH = 258;
466
var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
467
 
468
function smaller(tree, n, m, depth) {
469
    var tn2 = tree[n * 2];
470
    var tm2 = tree[m * 2];
471
    return (tn2 < tm2 || (tn2 == tm2 && depth[n] <= depth[m]));
472
}
473
 
474
function Deflate() {
475
 
476
    var that = this;
477
    var strm; // pointer back to this zlib stream
478
    var status; // as the name implies
479
    // pending_buf; // output still pending
480
    var pending_buf_size; // size of pending_buf
481
    // pending_out; // next pending byte to output to the stream
482
    // pending; // nb of bytes in the pending buffer
483
    var method; // STORED (for zip only) or DEFLATED
484
    var last_flush; // value of flush param for previous deflate call
485
 
486
    var w_size; // LZ77 window size (32K by default)
487
    var w_bits; // log2(w_size) (8..16)
488
    var w_mask; // w_size - 1
489
 
490
    var window;
491
    // Sliding window. Input bytes are read into the second half of the window,
492
    // and move to the first half later to keep a dictionary of at least wSize
493
    // bytes. With this organization, matches are limited to a distance of
494
    // wSize-MAX_MATCH bytes, but this ensures that IO is always
495
    // performed with a length multiple of the block size. Also, it limits
496
    // the window size to 64K, which is quite useful on MSDOS.
497
    // To do: use the user input buffer as sliding window.
498
 
499
    var window_size;
500
    // Actual size of window: 2*wSize, except when the user input buffer
501
    // is directly used as sliding window.
502
 
503
    var prev;
504
    // Link to older string with same hash index. To limit the size of this
505
    // array to 64K, this link is maintained only for the last 32K strings.
506
    // An index in this array is thus a window index modulo 32K.
507
 
508
    var head; // Heads of the hash chains or NIL.
509
 
510
    var ins_h; // hash index of string to be inserted
511
    var hash_size; // number of elements in hash table
512
    var hash_bits; // log2(hash_size)
513
    var hash_mask; // hash_size-1
514
 
515
    // Number of bits by which ins_h must be shifted at each input
516
    // step. It must be such that after MIN_MATCH steps, the oldest
517
    // byte no longer takes part in the hash key, that is:
518
    // hash_shift * MIN_MATCH >= hash_bits
519
    var hash_shift;
520
 
521
    // Window position at the beginning of the current output block. Gets
522
    // negative when the window is moved backwards.
523
 
524
    var block_start;
525
 
526
    var match_length; // length of best match
527
    var prev_match; // previous match
528
    var match_available; // set if previous match exists
529
    var strstart; // start of string to insert
530
    var match_start; // start of matching string
531
    var lookahead; // number of valid bytes ahead in window
532
 
533
    // Length of the best match at previous step. Matches not greater than this
534
    // are discarded. This is used in the lazy match evaluation.
535
    var prev_length;
536
 
537
    // To speed up deflation, hash chains are never searched beyond this
538
    // length. A higher limit improves compression ratio but degrades the speed.
539
    var max_chain_length;
540
 
541
    // Attempt to find a better match only when the current match is strictly
542
    // smaller than this value. This mechanism is used only for compression
543
    // levels >= 4.
544
    var max_lazy_match;
545
 
546
    // Insert new strings in the hash table only if the match length is not
547
    // greater than this length. This saves time but degrades compression.
548
    // max_insert_length is used only for compression levels <= 3.
549
 
550
    var level; // compression level (1..9)
551
    var strategy; // favor or force Huffman coding
552
 
553
    // Use a faster search when the previous match is longer than this
554
    var good_match;
555
 
556
    // Stop searching when current match exceeds this
557
    var nice_match;
558
 
559
    var dyn_ltree; // literal and length tree
560
    var dyn_dtree; // distance tree
561
    var bl_tree; // Huffman tree for bit lengths
562
 
563
    var l_desc = new Tree(); // desc for literal tree
564
    var d_desc = new Tree(); // desc for distance tree
565
    var bl_desc = new Tree(); // desc for bit length tree
566
 
567
    // that.heap_len; // number of elements in the heap
568
    // that.heap_max; // element of largest frequency
569
    // The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
570
    // The same heap array is used to build all trees.
571
 
572
    // Depth of each subtree used as tie breaker for trees of equal frequency
573
    that.depth = [];
574
 
575
    var l_buf; // index for literals or lengths */
576
 
577
    // Size of match buffer for literals/lengths. There are 4 reasons for
578
    // limiting lit_bufsize to 64K:
579
    // - frequencies can be kept in 16 bit counters
580
    // - if compression is not successful for the first block, all input
581
    // data is still in the window so we can still emit a stored block even
582
    // when input comes from standard input. (This can also be done for
583
    // all blocks if lit_bufsize is not greater than 32K.)
584
    // - if compression is not successful for a file smaller than 64K, we can
585
    // even emit a stored file instead of a stored block (saving 5 bytes).
586
    // This is applicable only for zip (not gzip or zlib).
587
    // - creating new Huffman trees less frequently may not provide fast
588
    // adaptation to changes in the input data statistics. (Take for
589
    // example a binary file with poorly compressible code followed by
590
    // a highly compressible string table.) Smaller buffer sizes give
591
    // fast adaptation but have of course the overhead of transmitting
592
    // trees more frequently.
593
    // - I can't count above 4
594
    var lit_bufsize;
595
 
596
    var last_lit; // running index in l_buf
597
 
598
    // Buffer for distances. To simplify the code, d_buf and l_buf have
599
    // the same number of elements. To use different lengths, an extra flag
600
    // array would be necessary.
601
 
602
    var d_buf; // index of pendig_buf
603
 
604
    // that.opt_len; // bit length of current block with optimal trees
605
    // that.static_len; // bit length of current block with static trees
606
    var matches; // number of string matches in current block
607
    var last_eob_len; // bit length of EOB code for last block
608
 
609
    // Output buffer. bits are inserted starting at the bottom (least
610
    // significant bits).
611
    var bi_buf;
612
 
613
    // Number of valid bits in bi_buf. All bits above the last valid bit
614
    // are always zero.
615
    var bi_valid;
616
 
617
    // number of codes at each bit length for an optimal tree
618
    that.bl_count = [];
619
 
620
    // heap used to build the Huffman trees
621
    that.heap = [];
622
 
623
    dyn_ltree = [];
624
    dyn_dtree = [];
625
    bl_tree = [];
626
 
627
    function lm_init() {
628
        var i;
629
        window_size = 2 * w_size;
630
 
631
        head[hash_size - 1] = 0;
632
        for (i = 0; i < hash_size - 1; i++) {
633
            head[i] = 0;
634
        }
635
 
636
        // Set the default configuration parameters:
637
        max_lazy_match = config_table[level].max_lazy;
638
        good_match = config_table[level].good_length;
639
        nice_match = config_table[level].nice_length;
640
        max_chain_length = config_table[level].max_chain;
641
 
642
        strstart = 0;
643
        block_start = 0;
644
        lookahead = 0;
645
        match_length = prev_length = MIN_MATCH - 1;
646
        match_available = 0;
647
        ins_h = 0;
648
    }
649
 
650
    function init_block() {
651
        var i;
652
        // Initialize the trees.
653
        for (i = 0; i < L_CODES; i++)
654
            dyn_ltree[i * 2] = 0;
655
        for (i = 0; i < D_CODES; i++)
656
            dyn_dtree[i * 2] = 0;
657
        for (i = 0; i < BL_CODES; i++)
658
            bl_tree[i * 2] = 0;
659
 
660
        dyn_ltree[END_BLOCK * 2] = 1;
661
        that.opt_len = that.static_len = 0;
662
        last_lit = matches = 0;
663
    }
664
 
665
    // Initialize the tree data structures for a new zlib stream.
666
    function tr_init() {
667
 
668
        l_desc.dyn_tree = dyn_ltree;
669
        l_desc.stat_desc = StaticTree.static_l_desc;
670
 
671
        d_desc.dyn_tree = dyn_dtree;
672
        d_desc.stat_desc = StaticTree.static_d_desc;
673
 
674
        bl_desc.dyn_tree = bl_tree;
675
        bl_desc.stat_desc = StaticTree.static_bl_desc;
676
 
677
        bi_buf = 0;
678
        bi_valid = 0;
679
        last_eob_len = 8; // enough lookahead for inflate
680
 
681
        // Initialize the first block of the first file:
682
        init_block();
683
    }
684
 
685
    // Restore the heap property by moving down the tree starting at node k,
686
    // exchanging a node with the smallest of its two sons if necessary,
687
    // stopping
688
    // when the heap property is re-established (each father smaller than its
689
    // two sons).
690
    that.pqdownheap = function(tree, // the tree to restore
691
    k // node to move down
692
    ) {
693
        var heap = that.heap;
694
        var v = heap[k];
695
        var j = k << 1; // left son of k
696
        while (j <= that.heap_len) {
697
            // Set j to the smallest of the two sons:
698
            if (j < that.heap_len && smaller(tree, heap[j + 1], heap[j], that.depth)) {
699
                j++;
700
            }
701
            // Exit if v is smaller than both sons
702
            if (smaller(tree, v, heap[j], that.depth))
703
                break;
704
 
705
            // Exchange v with the smallest son
706
            heap[k] = heap[j];
707
            k = j;
708
            // And continue down the tree, setting j to the left son of k
709
            j <<= 1;
710
        }
711
        heap[k] = v;
712
    };
713
 
714
    // Scan a literal or distance tree to determine the frequencies of the codes
715
    // in the bit length tree.
716
    function scan_tree(tree,// the tree to be scanned
717
    max_code // and its largest code of non zero frequency
718
    ) {
719
        var n; // iterates over all tree elements
720
        var prevlen = -1; // last emitted length
721
        var curlen; // length of current code
722
        var nextlen = tree[0 * 2 + 1]; // length of next code
723
        var count = 0; // repeat count of the current code
724
        var max_count = 7; // max repeat count
725
        var min_count = 4; // min repeat count
726
 
727
        if (nextlen === 0) {
728
            max_count = 138;
729
            min_count = 3;
730
        }
731
        tree[(max_code + 1) * 2 + 1] = 0xffff; // guard
732
 
733
        for (n = 0; n <= max_code; n++) {
734
            curlen = nextlen;
735
            nextlen = tree[(n + 1) * 2 + 1];
736
            if (++count < max_count && curlen == nextlen) {
737
                continue;
738
            } else if (count < min_count) {
739
                bl_tree[curlen * 2] += count;
740
            } else if (curlen !== 0) {
741
                if (curlen != prevlen)
742
                    bl_tree[curlen * 2]++;
743
                bl_tree[REP_3_6 * 2]++;
744
            } else if (count <= 10) {
745
                bl_tree[REPZ_3_10 * 2]++;
746
            } else {
747
                bl_tree[REPZ_11_138 * 2]++;
748
            }
749
            count = 0;
750
            prevlen = curlen;
751
            if (nextlen === 0) {
752
                max_count = 138;
753
                min_count = 3;
754
            } else if (curlen == nextlen) {
755
                max_count = 6;
756
                min_count = 3;
757
            } else {
758
                max_count = 7;
759
                min_count = 4;
760
            }
761
        }
762
    }
763
 
764
    // Construct the Huffman tree for the bit lengths and return the index in
765
    // bl_order of the last bit length code to send.
766
    function build_bl_tree() {
767
        var max_blindex; // index of last bit length code of non zero freq
768
 
769
        // Determine the bit length frequencies for literal and distance trees
770
        scan_tree(dyn_ltree, l_desc.max_code);
771
        scan_tree(dyn_dtree, d_desc.max_code);
772
 
773
        // Build the bit length tree:
774
        bl_desc.build_tree(that);
775
        // opt_len now includes the length of the tree representations, except
776
        // the lengths of the bit lengths codes and the 5+5+4 bits for the
777
        // counts.
778
 
779
        // Determine the number of bit length codes to send. The pkzip format
780
        // requires that at least 4 bit length codes be sent. (appnote.txt says
781
        // 3 but the actual value used is 4.)
782
        for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
783
            if (bl_tree[Tree.bl_order[max_blindex] * 2 + 1] !== 0)
784
                break;
785
        }
786
        // Update opt_len to include the bit length tree and counts
787
        that.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
788
 
789
        return max_blindex;
790
    }
791
 
792
    // Output a byte on the stream.
793
    // IN assertion: there is enough room in pending_buf.
794
    function put_byte(p) {
795
        that.pending_buf[that.pending++] = p;
796
    }
797
 
798
    function put_short(w) {
799
        put_byte(w & 0xff);
800
        put_byte((w >>> 8) & 0xff);
801
    }
802
 
803
    function putShortMSB(b) {
804
        put_byte((b >> 8) & 0xff);
805
        put_byte((b & 0xff) & 0xff);
806
    }
807
 
808
    function send_bits(value, length) {
809
        var val, len = length;
810
        if (bi_valid > Buf_size - len) {
811
            val = value;
812
            // bi_buf |= (val << bi_valid);
813
            bi_buf |= ((val << bi_valid) & 0xffff);
814
            put_short(bi_buf);
815
            bi_buf = val >>> (Buf_size - bi_valid);
816
            bi_valid += len - Buf_size;
817
        } else {
818
            // bi_buf |= (value) << bi_valid;
819
            bi_buf |= (((value) << bi_valid) & 0xffff);
820
            bi_valid += len;
821
        }
822
    }
823
 
824
    function send_code(c, tree) {
825
        var c2 = c * 2;
826
        send_bits(tree[c2] & 0xffff, tree[c2 + 1] & 0xffff);
827
    }
828
 
829
    // Send a literal or distance tree in compressed form, using the codes in
830
    // bl_tree.
831
    function send_tree(tree,// the tree to be sent
832
    max_code // and its largest code of non zero frequency
833
    ) {
834
        var n; // iterates over all tree elements
835
        var prevlen = -1; // last emitted length
836
        var curlen; // length of current code
837
        var nextlen = tree[0 * 2 + 1]; // length of next code
838
        var count = 0; // repeat count of the current code
839
        var max_count = 7; // max repeat count
840
        var min_count = 4; // min repeat count
841
 
842
        if (nextlen === 0) {
843
            max_count = 138;
844
            min_count = 3;
845
        }
846
 
847
        for (n = 0; n <= max_code; n++) {
848
            curlen = nextlen;
849
            nextlen = tree[(n + 1) * 2 + 1];
850
            if (++count < max_count && curlen == nextlen) {
851
                continue;
852
            } else if (count < min_count) {
853
                do {
854
                    send_code(curlen, bl_tree);
855
                } while (--count !== 0);
856
            } else if (curlen !== 0) {
857
                if (curlen != prevlen) {
858
                    send_code(curlen, bl_tree);
859
                    count--;
860
                }
861
                send_code(REP_3_6, bl_tree);
862
                send_bits(count - 3, 2);
863
            } else if (count <= 10) {
864
                send_code(REPZ_3_10, bl_tree);
865
                send_bits(count - 3, 3);
866
            } else {
867
                send_code(REPZ_11_138, bl_tree);
868
                send_bits(count - 11, 7);
869
            }
870
            count = 0;
871
            prevlen = curlen;
872
            if (nextlen === 0) {
873
                max_count = 138;
874
                min_count = 3;
875
            } else if (curlen == nextlen) {
876
                max_count = 6;
877
                min_count = 3;
878
            } else {
879
                max_count = 7;
880
                min_count = 4;
881
            }
882
        }
883
    }
884
 
885
    // Send the header for a block using dynamic Huffman trees: the counts, the
886
    // lengths of the bit length codes, the literal tree and the distance tree.
887
    // IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
888
    function send_all_trees(lcodes, dcodes, blcodes) {
889
        var rank; // index in bl_order
890
 
891
        send_bits(lcodes - 257, 5); // not +255 as stated in appnote.txt
892
        send_bits(dcodes - 1, 5);
893
        send_bits(blcodes - 4, 4); // not -3 as stated in appnote.txt
894
        for (rank = 0; rank < blcodes; rank++) {
895
            send_bits(bl_tree[Tree.bl_order[rank] * 2 + 1], 3);
896
        }
897
        send_tree(dyn_ltree, lcodes - 1); // literal tree
898
        send_tree(dyn_dtree, dcodes - 1); // distance tree
899
    }
900
 
901
    // Flush the bit buffer, keeping at most 7 bits in it.
902
    function bi_flush() {
903
        if (bi_valid == 16) {
904
            put_short(bi_buf);
905
            bi_buf = 0;
906
            bi_valid = 0;
907
        } else if (bi_valid >= 8) {
908
            put_byte(bi_buf & 0xff);
909
            bi_buf >>>= 8;
910
            bi_valid -= 8;
911
        }
912
    }
913
 
914
    // Send one empty static block to give enough lookahead for inflate.
915
    // This takes 10 bits, of which 7 may remain in the bit buffer.
916
    // The current inflate code requires 9 bits of lookahead. If the
917
    // last two codes for the previous block (real code plus EOB) were coded
918
    // on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
919
    // the last real code. In this case we send two empty static blocks instead
920
    // of one. (There are no problems if the previous block is stored or fixed.)
921
    // To simplify the code, we assume the worst case of last real code encoded
922
    // on one bit only.
923
    function _tr_align() {
924
        send_bits(STATIC_TREES << 1, 3);
925
        send_code(END_BLOCK, StaticTree.static_ltree);
926
 
927
        bi_flush();
928
 
929
        // Of the 10 bits for the empty block, we have already sent
930
        // (10 - bi_valid) bits. The lookahead for the last real code (before
931
        // the EOB of the previous block) was thus at least one plus the length
932
        // of the EOB plus what we have just sent of the empty static block.
933
        if (1 + last_eob_len + 10 - bi_valid < 9) {
934
            send_bits(STATIC_TREES << 1, 3);
935
            send_code(END_BLOCK, StaticTree.static_ltree);
936
            bi_flush();
937
        }
938
        last_eob_len = 7;
939
    }
940
 
941
    // Save the match info and tally the frequency counts. Return true if
942
    // the current block must be flushed.
943
    function _tr_tally(dist, // distance of matched string
944
    lc // match length-MIN_MATCH or unmatched char (if dist==0)
945
    ) {
946
        var out_length, in_length, dcode;
947
        that.pending_buf[d_buf + last_lit * 2] = (dist >>> 8) & 0xff;
948
        that.pending_buf[d_buf + last_lit * 2 + 1] = dist & 0xff;
949
 
950
        that.pending_buf[l_buf + last_lit] = lc & 0xff;
951
        last_lit++;
952
 
953
        if (dist === 0) {
954
            // lc is the unmatched char
955
            dyn_ltree[lc * 2]++;
956
        } else {
957
            matches++;
958
            // Here, lc is the match length - MIN_MATCH
959
            dist--; // dist = match distance - 1
960
            dyn_ltree[(Tree._length_code[lc] + LITERALS + 1) * 2]++;
961
            dyn_dtree[Tree.d_code(dist) * 2]++;
962
        }
963
 
964
        if ((last_lit & 0x1fff) === 0 && level > 2) {
965
            // Compute an upper bound for the compressed length
966
            out_length = last_lit * 8;
967
            in_length = strstart - block_start;
968
            for (dcode = 0; dcode < D_CODES; dcode++) {
969
                out_length += dyn_dtree[dcode * 2] * (5 + Tree.extra_dbits[dcode]);
970
            }
971
            out_length >>>= 3;
972
            if ((matches < Math.floor(last_lit / 2)) && out_length < Math.floor(in_length / 2))
973
                return true;
974
        }
975
 
976
        return (last_lit == lit_bufsize - 1);
977
        // We avoid equality with lit_bufsize because of wraparound at 64K
978
        // on 16 bit machines and because stored blocks are restricted to
979
        // 64K-1 bytes.
980
    }
981
 
982
    // Send the block data compressed using the given Huffman trees
983
    function compress_block(ltree, dtree) {
984
        var dist; // distance of matched string
985
        var lc; // match length or unmatched char (if dist === 0)
986
        var lx = 0; // running index in l_buf
987
        var code; // the code to send
988
        var extra; // number of extra bits to send
989
 
990
        if (last_lit !== 0) {
991
            do {
992
                dist = ((that.pending_buf[d_buf + lx * 2] << 8) & 0xff00) | (that.pending_buf[d_buf + lx * 2 + 1] & 0xff);
993
                lc = (that.pending_buf[l_buf + lx]) & 0xff;
994
                lx++;
995
 
996
                if (dist === 0) {
997
                    send_code(lc, ltree); // send a literal byte
998
                } else {
999
                    // Here, lc is the match length - MIN_MATCH
1000
                    code = Tree._length_code[lc];
1001
 
1002
                    send_code(code + LITERALS + 1, ltree); // send the length
1003
                    // code
1004
                    extra = Tree.extra_lbits[code];
1005
                    if (extra !== 0) {
1006
                        lc -= Tree.base_length[code];
1007
                        send_bits(lc, extra); // send the extra length bits
1008
                    }
1009
                    dist--; // dist is now the match distance - 1
1010
                    code = Tree.d_code(dist);
1011
 
1012
                    send_code(code, dtree); // send the distance code
1013
                    extra = Tree.extra_dbits[code];
1014
                    if (extra !== 0) {
1015
                        dist -= Tree.base_dist[code];
1016
                        send_bits(dist, extra); // send the extra distance bits
1017
                    }
1018
                } // literal or match pair ?
1019
 
1020
                // Check that the overlay between pending_buf and d_buf+l_buf is
1021
                // ok:
1022
            } while (lx < last_lit);
1023
        }
1024
 
1025
        send_code(END_BLOCK, ltree);
1026
        last_eob_len = ltree[END_BLOCK * 2 + 1];
1027
    }
1028
 
1029
    // Flush the bit buffer and align the output on a byte boundary
1030
    function bi_windup() {
1031
        if (bi_valid > 8) {
1032
            put_short(bi_buf);
1033
        } else if (bi_valid > 0) {
1034
            put_byte(bi_buf & 0xff);
1035
        }
1036
        bi_buf = 0;
1037
        bi_valid = 0;
1038
    }
1039
 
1040
    // Copy a stored block, storing first the length and its
1041
    // one's complement if requested.
1042
    function copy_block(buf, // the input data
1043
    len, // its length
1044
    header // true if block header must be written
1045
    ) {
1046
        bi_windup(); // align on byte boundary
1047
        last_eob_len = 8; // enough lookahead for inflate
1048
 
1049
        if (header) {
1050
            put_short(len);
1051
            put_short(~len);
1052
        }
1053
 
1054
        that.pending_buf.set(window.subarray(buf, buf + len), that.pending);
1055
        that.pending += len;
1056
    }
1057
 
1058
    // Send a stored block
1059
    function _tr_stored_block(buf, // input block
1060
    stored_len, // length of input block
1061
    eof // true if this is the last block for a file
1062
    ) {
1063
        send_bits((STORED_BLOCK << 1) + (eof ? 1 : 0), 3); // send block type
1064
        copy_block(buf, stored_len, true); // with header
1065
    }
1066
 
1067
    // Determine the best encoding for the current block: dynamic trees, static
1068
    // trees or store, and output the encoded block to the zip file.
1069
    function _tr_flush_block(buf, // input block, or NULL if too old
1070
    stored_len, // length of input block
1071
    eof // true if this is the last block for a file
1072
    ) {
1073
        var opt_lenb, static_lenb;// opt_len and static_len in bytes
1074
        var max_blindex = 0; // index of last bit length code of non zero freq
1075
 
1076
        // Build the Huffman trees unless a stored block is forced
1077
        if (level > 0) {
1078
            // Construct the literal and distance trees
1079
            l_desc.build_tree(that);
1080
 
1081
            d_desc.build_tree(that);
1082
 
1083
            // At this point, opt_len and static_len are the total bit lengths
1084
            // of
1085
            // the compressed block data, excluding the tree representations.
1086
 
1087
            // Build the bit length tree for the above two trees, and get the
1088
            // index
1089
            // in bl_order of the last bit length code to send.
1090
            max_blindex = build_bl_tree();
1091
 
1092
            // Determine the best encoding. Compute first the block length in
1093
            // bytes
1094
            opt_lenb = (that.opt_len + 3 + 7) >>> 3;
1095
            static_lenb = (that.static_len + 3 + 7) >>> 3;
1096
 
1097
            if (static_lenb <= opt_lenb)
1098
                opt_lenb = static_lenb;
1099
        } else {
1100
            opt_lenb = static_lenb = stored_len + 5; // force a stored block
1101
        }
1102
 
1103
        if ((stored_len + 4 <= opt_lenb) && buf != -1) {
1104
            // 4: two words for the lengths
1105
            // The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
1106
            // Otherwise we can't have processed more than WSIZE input bytes
1107
            // since
1108
            // the last block flush, because compression would have been
1109
            // successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
1110
            // transform a block into a stored block.
1111
            _tr_stored_block(buf, stored_len, eof);
1112
        } else if (static_lenb == opt_lenb) {
1113
            send_bits((STATIC_TREES << 1) + (eof ? 1 : 0), 3);
1114
            compress_block(StaticTree.static_ltree, StaticTree.static_dtree);
1115
        } else {
1116
            send_bits((DYN_TREES << 1) + (eof ? 1 : 0), 3);
1117
            send_all_trees(l_desc.max_code + 1, d_desc.max_code + 1, max_blindex + 1);
1118
            compress_block(dyn_ltree, dyn_dtree);
1119
        }
1120
 
1121
        // The above check is made mod 2^32, for files larger than 512 MB
1122
        // and uLong implemented on 32 bits.
1123
 
1124
        init_block();
1125
 
1126
        if (eof) {
1127
            bi_windup();
1128
        }
1129
    }
1130
 
1131
    function flush_block_only(eof) {
1132
        _tr_flush_block(block_start >= 0 ? block_start : -1, strstart - block_start, eof);
1133
        block_start = strstart;
1134
        strm.flush_pending();
1135
    }
1136
 
1137
    // Fill the window when the lookahead becomes insufficient.
1138
    // Updates strstart and lookahead.
1139
    //
1140
    // IN assertion: lookahead < MIN_LOOKAHEAD
1141
    // OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
1142
    // At least one byte has been read, or avail_in === 0; reads are
1143
    // performed for at least two bytes (required for the zip translate_eol
1144
    // option -- not supported here).
1145
    function fill_window() {
1146
        var n, m;
1147
        var p;
1148
        var more; // Amount of free space at the end of the window.
1149
 
1150
        do {
1151
            more = (window_size - lookahead - strstart);
1152
 
1153
            // Deal with !@#$% 64K limit:
1154
            if (more === 0 && strstart === 0 && lookahead === 0) {
1155
                more = w_size;
1156
            } else if (more == -1) {
1157
                // Very unlikely, but possible on 16 bit machine if strstart ==
1158
                // 0
1159
                // and lookahead == 1 (input done one byte at time)
1160
                more--;
1161
 
1162
                // If the window is almost full and there is insufficient
1163
                // lookahead,
1164
                // move the upper half to the lower one to make room in the
1165
                // upper half.
1166
            } else if (strstart >= w_size + w_size - MIN_LOOKAHEAD) {
1167
                window.set(window.subarray(w_size, w_size + w_size), 0);
1168
 
1169
                match_start -= w_size;
1170
                strstart -= w_size; // we now have strstart >= MAX_DIST
1171
                block_start -= w_size;
1172
 
1173
                // Slide the hash table (could be avoided with 32 bit values
1174
                // at the expense of memory usage). We slide even when level ==
1175
                // 0
1176
                // to keep the hash table consistent if we switch back to level
1177
                // > 0
1178
                // later. (Using level 0 permanently is not an optimal usage of
1179
                // zlib, so we don't care about this pathological case.)
1180
 
1181
                n = hash_size;
1182
                p = n;
1183
                do {
1184
                    m = (head[--p] & 0xffff);
1185
                    head[p] = (m >= w_size ? m - w_size : 0);
1186
                } while (--n !== 0);
1187
 
1188
                n = w_size;
1189
                p = n;
1190
                do {
1191
                    m = (prev[--p] & 0xffff);
1192
                    prev[p] = (m >= w_size ? m - w_size : 0);
1193
                    // If n is not on any hash chain, prev[n] is garbage but
1194
                    // its value will never be used.
1195
                } while (--n !== 0);
1196
                more += w_size;
1197
            }
1198
 
1199
            if (strm.avail_in === 0)
1200
                return;
1201
 
1202
            // If there was no sliding:
1203
            // strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
1204
            // more == window_size - lookahead - strstart
1205
            // => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
1206
            // => more >= window_size - 2*WSIZE + 2
1207
            // In the BIG_MEM or MMAP case (not yet supported),
1208
            // window_size == input_size + MIN_LOOKAHEAD &&
1209
            // strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
1210
            // Otherwise, window_size == 2*WSIZE so more >= 2.
1211
            // If there was sliding, more >= WSIZE. So in all cases, more >= 2.
1212
 
1213
            n = strm.read_buf(window, strstart + lookahead, more);
1214
            lookahead += n;
1215
 
1216
            // Initialize the hash value now that we have some input:
1217
            if (lookahead >= MIN_MATCH) {
1218
                ins_h = window[strstart] & 0xff;
1219
                ins_h = (((ins_h) << hash_shift) ^ (window[strstart + 1] & 0xff)) & hash_mask;
1220
            }
1221
            // If the whole input has less than MIN_MATCH bytes, ins_h is
1222
            // garbage,
1223
            // but this is not important since only literal bytes will be
1224
            // emitted.
1225
        } while (lookahead < MIN_LOOKAHEAD && strm.avail_in !== 0);
1226
    }
1227
 
1228
    // Copy without compression as much as possible from the input stream,
1229
    // return
1230
    // the current block state.
1231
    // This function does not insert new strings in the dictionary since
1232
    // uncompressible data is probably not useful. This function is used
1233
    // only for the level=0 compression option.
1234
    // NOTE: this function should be optimized to avoid extra copying from
1235
    // window to pending_buf.
1236
    function deflate_stored(flush) {
1237
        // Stored blocks are limited to 0xffff bytes, pending_buf is limited
1238
        // to pending_buf_size, and each stored block has a 5 byte header:
1239
 
1240
        var max_block_size = 0xffff;
1241
        var max_start;
1242
 
1243
        if (max_block_size > pending_buf_size - 5) {
1244
            max_block_size = pending_buf_size - 5;
1245
        }
1246
 
1247
        // Copy as much as possible from input to output:
1248
        while (true) {
1249
            // Fill the window as much as possible:
1250
            if (lookahead <= 1) {
1251
                fill_window();
1252
                if (lookahead === 0 && flush == Z_NO_FLUSH)
1253
                    return NeedMore;
1254
                if (lookahead === 0)
1255
                    break; // flush the current block
1256
            }
1257
 
1258
            strstart += lookahead;
1259
            lookahead = 0;
1260
 
1261
            // Emit a stored block if pending_buf will be full:
1262
            max_start = block_start + max_block_size;
1263
            if (strstart === 0 || strstart >= max_start) {
1264
                // strstart === 0 is possible when wraparound on 16-bit machine
1265
                lookahead = (strstart - max_start);
1266
                strstart = max_start;
1267
 
1268
                flush_block_only(false);
1269
                if (strm.avail_out === 0)
1270
                    return NeedMore;
1271
 
1272
            }
1273
 
1274
            // Flush if we may have to slide, otherwise block_start may become
1275
            // negative and the data will be gone:
1276
            if (strstart - block_start >= w_size - MIN_LOOKAHEAD) {
1277
                flush_block_only(false);
1278
                if (strm.avail_out === 0)
1279
                    return NeedMore;
1280
            }
1281
        }
1282
 
1283
        flush_block_only(flush == Z_FINISH);
1284
        if (strm.avail_out === 0)
1285
            return (flush == Z_FINISH) ? FinishStarted : NeedMore;
1286
 
1287
        return flush == Z_FINISH ? FinishDone : BlockDone;
1288
    }
1289
 
1290
    function longest_match(cur_match) {
1291
        var chain_length = max_chain_length; // max hash chain length
1292
        var scan = strstart; // current string
1293
        var match; // matched string
1294
        var len; // length of current match
1295
        var best_len = prev_length; // best match length so far
1296
        var limit = strstart > (w_size - MIN_LOOKAHEAD) ? strstart - (w_size - MIN_LOOKAHEAD) : 0;
1297
        var _nice_match = nice_match;
1298
 
1299
        // Stop when cur_match becomes <= limit. To simplify the code,
1300
        // we prevent matches with the string of window index 0.
1301
 
1302
        var wmask = w_mask;
1303
 
1304
        var strend = strstart + MAX_MATCH;
1305
        var scan_end1 = window[scan + best_len - 1];
1306
        var scan_end = window[scan + best_len];
1307
 
1308
        // The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of
1309
        // 16.
1310
        // It is easy to get rid of this optimization if necessary.
1311
 
1312
        // Do not waste too much time if we already have a good match:
1313
        if (prev_length >= good_match) {
1314
            chain_length >>= 2;
1315
        }
1316
 
1317
        // Do not look for matches beyond the end of the input. This is
1318
        // necessary
1319
        // to make deflate deterministic.
1320
        if (_nice_match > lookahead)
1321
            _nice_match = lookahead;
1322
 
1323
        do {
1324
            match = cur_match;
1325
 
1326
            // Skip to next match if the match length cannot increase
1327
            // or if the match length is less than 2:
1328
            if (window[match + best_len] != scan_end || window[match + best_len - 1] != scan_end1 || window[match] != window[scan]
1329
                    || window[++match] != window[scan + 1])
1330
                continue;
1331
 
1332
            // The check at best_len-1 can be removed because it will be made
1333
            // again later. (This heuristic is not always a win.)
1334
            // It is not necessary to compare scan[2] and match[2] since they
1335
            // are always equal when the other bytes match, given that
1336
            // the hash keys are equal and that HASH_BITS >= 8.
1337
            scan += 2;
1338
            match++;
1339
 
1340
            // We check for insufficient lookahead only every 8th comparison;
1341
            // the 256th check will be made at strstart+258.
1342
            do {
1343
            } while (window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match]
1344
                    && window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match]
1345
                    && window[++scan] == window[++match] && window[++scan] == window[++match] && scan < strend);
1346
 
1347
            len = MAX_MATCH - (strend - scan);
1348
            scan = strend - MAX_MATCH;
1349
 
1350
            if (len > best_len) {
1351
                match_start = cur_match;
1352
                best_len = len;
1353
                if (len >= _nice_match)
1354
                    break;
1355
                scan_end1 = window[scan + best_len - 1];
1356
                scan_end = window[scan + best_len];
1357
            }
1358
 
1359
        } while ((cur_match = (prev[cur_match & wmask] & 0xffff)) > limit && --chain_length !== 0);
1360
 
1361
        if (best_len <= lookahead)
1362
            return best_len;
1363
        return lookahead;
1364
    }
1365
 
1366
    // Compress as much as possible from the input stream, return the current
1367
    // block state.
1368
    // This function does not perform lazy evaluation of matches and inserts
1369
    // new strings in the dictionary only for unmatched strings or for short
1370
    // matches. It is used only for the fast compression options.
1371
    function deflate_fast(flush) {
1372
        // short hash_head = 0; // head of the hash chain
1373
        var hash_head = 0; // head of the hash chain
1374
        var bflush; // set if current block must be flushed
1375
 
1376
        while (true) {
1377
            // Make sure that we always have enough lookahead, except
1378
            // at the end of the input file. We need MAX_MATCH bytes
1379
            // for the next match, plus MIN_MATCH bytes to insert the
1380
            // string following the next match.
1381
            if (lookahead < MIN_LOOKAHEAD) {
1382
                fill_window();
1383
                if (lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
1384
                    return NeedMore;
1385
                }
1386
                if (lookahead === 0)
1387
                    break; // flush the current block
1388
            }
1389
 
1390
            // Insert the string window[strstart .. strstart+2] in the
1391
            // dictionary, and set hash_head to the head of the hash chain:
1392
            if (lookahead >= MIN_MATCH) {
1393
                ins_h = (((ins_h) << hash_shift) ^ (window[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
1394
 
1395
                // prev[strstart&w_mask]=hash_head=head[ins_h];
1396
                hash_head = (head[ins_h] & 0xffff);
1397
                prev[strstart & w_mask] = head[ins_h];
1398
                head[ins_h] = strstart;
1399
            }
1400
 
1401
            // Find the longest match, discarding those <= prev_length.
1402
            // At this point we have always match_length < MIN_MATCH
1403
 
1404
            if (hash_head !== 0 && ((strstart - hash_head) & 0xffff) <= w_size - MIN_LOOKAHEAD) {
1405
                // To simplify the code, we prevent matches with the string
1406
                // of window index 0 (in particular we have to avoid a match
1407
                // of the string with itself at the start of the input file).
1408
                if (strategy != Z_HUFFMAN_ONLY) {
1409
                    match_length = longest_match(hash_head);
1410
                }
1411
                // longest_match() sets match_start
1412
            }
1413
            if (match_length >= MIN_MATCH) {
1414
                // check_match(strstart, match_start, match_length);
1415
 
1416
                bflush = _tr_tally(strstart - match_start, match_length - MIN_MATCH);
1417
 
1418
                lookahead -= match_length;
1419
 
1420
                // Insert new strings in the hash table only if the match length
1421
                // is not too large. This saves time but degrades compression.
1422
                if (match_length <= max_lazy_match && lookahead >= MIN_MATCH) {
1423
                    match_length--; // string at strstart already in hash table
1424
                    do {
1425
                        strstart++;
1426
 
1427
                        ins_h = ((ins_h << hash_shift) ^ (window[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
1428
                        // prev[strstart&w_mask]=hash_head=head[ins_h];
1429
                        hash_head = (head[ins_h] & 0xffff);
1430
                        prev[strstart & w_mask] = head[ins_h];
1431
                        head[ins_h] = strstart;
1432
 
1433
                        // strstart never exceeds WSIZE-MAX_MATCH, so there are
1434
                        // always MIN_MATCH bytes ahead.
1435
                    } while (--match_length !== 0);
1436
                    strstart++;
1437
                } else {
1438
                    strstart += match_length;
1439
                    match_length = 0;
1440
                    ins_h = window[strstart] & 0xff;
1441
 
1442
                    ins_h = (((ins_h) << hash_shift) ^ (window[strstart + 1] & 0xff)) & hash_mask;
1443
                    // If lookahead < MIN_MATCH, ins_h is garbage, but it does
1444
                    // not
1445
                    // matter since it will be recomputed at next deflate call.
1446
                }
1447
            } else {
1448
                // No match, output a literal byte
1449
 
1450
                bflush = _tr_tally(0, window[strstart] & 0xff);
1451
                lookahead--;
1452
                strstart++;
1453
            }
1454
            if (bflush) {
1455
 
1456
                flush_block_only(false);
1457
                if (strm.avail_out === 0)
1458
                    return NeedMore;
1459
            }
1460
        }
1461
 
1462
        flush_block_only(flush == Z_FINISH);
1463
        if (strm.avail_out === 0) {
1464
            if (flush == Z_FINISH)
1465
                return FinishStarted;
1466
            else
1467
                return NeedMore;
1468
        }
1469
        return flush == Z_FINISH ? FinishDone : BlockDone;
1470
    }
1471
 
1472
    // Same as above, but achieves better compression. We use a lazy
1473
    // evaluation for matches: a match is finally adopted only if there is
1474
    // no better match at the next window position.
1475
    function deflate_slow(flush) {
1476
        // short hash_head = 0; // head of hash chain
1477
        var hash_head = 0; // head of hash chain
1478
        var bflush; // set if current block must be flushed
1479
        var max_insert;
1480
 
1481
        // Process the input block.
1482
        while (true) {
1483
            // Make sure that we always have enough lookahead, except
1484
            // at the end of the input file. We need MAX_MATCH bytes
1485
            // for the next match, plus MIN_MATCH bytes to insert the
1486
            // string following the next match.
1487
 
1488
            if (lookahead < MIN_LOOKAHEAD) {
1489
                fill_window();
1490
                if (lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
1491
                    return NeedMore;
1492
                }
1493
                if (lookahead === 0)
1494
                    break; // flush the current block
1495
            }
1496
 
1497
            // Insert the string window[strstart .. strstart+2] in the
1498
            // dictionary, and set hash_head to the head of the hash chain:
1499
 
1500
            if (lookahead >= MIN_MATCH) {
1501
                ins_h = (((ins_h) << hash_shift) ^ (window[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
1502
                // prev[strstart&w_mask]=hash_head=head[ins_h];
1503
                hash_head = (head[ins_h] & 0xffff);
1504
                prev[strstart & w_mask] = head[ins_h];
1505
                head[ins_h] = strstart;
1506
            }
1507
 
1508
            // Find the longest match, discarding those <= prev_length.
1509
            prev_length = match_length;
1510
            prev_match = match_start;
1511
            match_length = MIN_MATCH - 1;
1512
 
1513
            if (hash_head !== 0 && prev_length < max_lazy_match && ((strstart - hash_head) & 0xffff) <= w_size - MIN_LOOKAHEAD) {
1514
                // To simplify the code, we prevent matches with the string
1515
                // of window index 0 (in particular we have to avoid a match
1516
                // of the string with itself at the start of the input file).
1517
 
1518
                if (strategy != Z_HUFFMAN_ONLY) {
1519
                    match_length = longest_match(hash_head);
1520
                }
1521
                // longest_match() sets match_start
1522
 
1523
                if (match_length <= 5 && (strategy == Z_FILTERED || (match_length == MIN_MATCH && strstart - match_start > 4096))) {
1524
 
1525
                    // If prev_match is also MIN_MATCH, match_start is garbage
1526
                    // but we will ignore the current match anyway.
1527
                    match_length = MIN_MATCH - 1;
1528
                }
1529
            }
1530
 
1531
            // If there was a match at the previous step and the current
1532
            // match is not better, output the previous match:
1533
            if (prev_length >= MIN_MATCH && match_length <= prev_length) {
1534
                max_insert = strstart + lookahead - MIN_MATCH;
1535
                // Do not insert strings in hash table beyond this.
1536
 
1537
                // check_match(strstart-1, prev_match, prev_length);
1538
 
1539
                bflush = _tr_tally(strstart - 1 - prev_match, prev_length - MIN_MATCH);
1540
 
1541
                // Insert in hash table all strings up to the end of the match.
1542
                // strstart-1 and strstart are already inserted. If there is not
1543
                // enough lookahead, the last two strings are not inserted in
1544
                // the hash table.
1545
                lookahead -= prev_length - 1;
1546
                prev_length -= 2;
1547
                do {
1548
                    if (++strstart <= max_insert) {
1549
                        ins_h = (((ins_h) << hash_shift) ^ (window[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
1550
                        // prev[strstart&w_mask]=hash_head=head[ins_h];
1551
                        hash_head = (head[ins_h] & 0xffff);
1552
                        prev[strstart & w_mask] = head[ins_h];
1553
                        head[ins_h] = strstart;
1554
                    }
1555
                } while (--prev_length !== 0);
1556
                match_available = 0;
1557
                match_length = MIN_MATCH - 1;
1558
                strstart++;
1559
 
1560
                if (bflush) {
1561
                    flush_block_only(false);
1562
                    if (strm.avail_out === 0)
1563
                        return NeedMore;
1564
                }
1565
            } else if (match_available !== 0) {
1566
 
1567
                // If there was no match at the previous position, output a
1568
                // single literal. If there was a match but the current match
1569
                // is longer, truncate the previous match to a single literal.
1570
 
1571
                bflush = _tr_tally(0, window[strstart - 1] & 0xff);
1572
 
1573
                if (bflush) {
1574
                    flush_block_only(false);
1575
                }
1576
                strstart++;
1577
                lookahead--;
1578
                if (strm.avail_out === 0)
1579
                    return NeedMore;
1580
            } else {
1581
                // There is no previous match to compare with, wait for
1582
                // the next step to decide.
1583
 
1584
                match_available = 1;
1585
                strstart++;
1586
                lookahead--;
1587
            }
1588
        }
1589
 
1590
        if (match_available !== 0) {
1591
            bflush = _tr_tally(0, window[strstart - 1] & 0xff);
1592
            match_available = 0;
1593
        }
1594
        flush_block_only(flush == Z_FINISH);
1595
 
1596
        if (strm.avail_out === 0) {
1597
            if (flush == Z_FINISH)
1598
                return FinishStarted;
1599
            else
1600
                return NeedMore;
1601
        }
1602
 
1603
        return flush == Z_FINISH ? FinishDone : BlockDone;
1604
    }
1605
 
1606
    function deflateReset(strm) {
1607
        strm.total_in = strm.total_out = 0;
1608
        strm.msg = null; //
1609
 
1610
        that.pending = 0;
1611
        that.pending_out = 0;
1612
 
1613
        status = BUSY_STATE;
1614
 
1615
        last_flush = Z_NO_FLUSH;
1616
 
1617
        tr_init();
1618
        lm_init();
1619
        return Z_OK;
1620
    }
1621
 
1622
    that.deflateInit = function(strm, _level, bits, _method, memLevel, _strategy) {
1623
        if (!_method)
1624
            _method = Z_DEFLATED;
1625
        if (!memLevel)
1626
            memLevel = DEF_MEM_LEVEL;
1627
        if (!_strategy)
1628
            _strategy = Z_DEFAULT_STRATEGY;
1629
 
1630
        // byte[] my_version=ZLIB_VERSION;
1631
 
1632
        //
1633
        // if (!version || version[0] != my_version[0]
1634
        // || stream_size != sizeof(z_stream)) {
1635
        // return Z_VERSION_ERROR;
1636
        // }
1637
 
1638
        strm.msg = null;
1639
 
1640
        if (_level == Z_DEFAULT_COMPRESSION)
1641
            _level = 6;
1642
 
1643
        if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || _method != Z_DEFLATED || bits < 9 || bits > 15 || _level < 0 || _level > 9 || _strategy < 0
1644
                || _strategy > Z_HUFFMAN_ONLY) {
1645
            return Z_STREAM_ERROR;
1646
        }
1647
 
1648
        strm.dstate = that;
1649
 
1650
        w_bits = bits;
1651
        w_size = 1 << w_bits;
1652
        w_mask = w_size - 1;
1653
 
1654
        hash_bits = memLevel + 7;
1655
        hash_size = 1 << hash_bits;
1656
        hash_mask = hash_size - 1;
1657
        hash_shift = Math.floor((hash_bits + MIN_MATCH - 1) / MIN_MATCH);
1658
 
1659
        window = new Uint8Array(w_size * 2);
1660
        prev = [];
1661
        head = [];
1662
 
1663
        lit_bufsize = 1 << (memLevel + 6); // 16K elements by default
1664
 
1665
        // We overlay pending_buf and d_buf+l_buf. This works since the average
1666
        // output size for (length,distance) codes is <= 24 bits.
1667
        that.pending_buf = new Uint8Array(lit_bufsize * 4);
1668
        pending_buf_size = lit_bufsize * 4;
1669
 
1670
        d_buf = Math.floor(lit_bufsize / 2);
1671
        l_buf = (1 + 2) * lit_bufsize;
1672
 
1673
        level = _level;
1674
 
1675
        strategy = _strategy;
1676
        method = _method & 0xff;
1677
 
1678
        return deflateReset(strm);
1679
    };
1680
 
1681
    that.deflateEnd = function() {
1682
        if (status != INIT_STATE && status != BUSY_STATE && status != FINISH_STATE) {
1683
            return Z_STREAM_ERROR;
1684
        }
1685
        // Deallocate in reverse order of allocations:
1686
        that.pending_buf = null;
1687
        head = null;
1688
        prev = null;
1689
        window = null;
1690
        // free
1691
        that.dstate = null;
1692
        return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
1693
    };
1694
 
1695
    that.deflateParams = function(strm, _level, _strategy) {
1696
        var err = Z_OK;
1697
 
1698
        if (_level == Z_DEFAULT_COMPRESSION) {
1699
            _level = 6;
1700
        }
1701
        if (_level < 0 || _level > 9 || _strategy < 0 || _strategy > Z_HUFFMAN_ONLY) {
1702
            return Z_STREAM_ERROR;
1703
        }
1704
 
1705
        if (config_table[level].func != config_table[_level].func && strm.total_in !== 0) {
1706
            // Flush the last buffer:
1707
            err = strm.deflate(Z_PARTIAL_FLUSH);
1708
        }
1709
 
1710
        if (level != _level) {
1711
            level = _level;
1712
            max_lazy_match = config_table[level].max_lazy;
1713
            good_match = config_table[level].good_length;
1714
            nice_match = config_table[level].nice_length;
1715
            max_chain_length = config_table[level].max_chain;
1716
        }
1717
        strategy = _strategy;
1718
        return err;
1719
    };
1720
 
1721
    that.deflateSetDictionary = function(strm, dictionary, dictLength) {
1722
        var length = dictLength;
1723
        var n, index = 0;
1724
 
1725
        if (!dictionary || status != INIT_STATE)
1726
            return Z_STREAM_ERROR;
1727
 
1728
        if (length < MIN_MATCH)
1729
            return Z_OK;
1730
        if (length > w_size - MIN_LOOKAHEAD) {
1731
            length = w_size - MIN_LOOKAHEAD;
1732
            index = dictLength - length; // use the tail of the dictionary
1733
        }
1734
        window.set(dictionary.subarray(index, index + length), 0);
1735
 
1736
        strstart = length;
1737
        block_start = length;
1738
 
1739
        // Insert all strings in the hash table (except for the last two bytes).
1740
        // s->lookahead stays null, so s->ins_h will be recomputed at the next
1741
        // call of fill_window.
1742
 
1743
        ins_h = window[0] & 0xff;
1744
        ins_h = (((ins_h) << hash_shift) ^ (window[1] & 0xff)) & hash_mask;
1745
 
1746
        for (n = 0; n <= length - MIN_MATCH; n++) {
1747
            ins_h = (((ins_h) << hash_shift) ^ (window[(n) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
1748
            prev[n & w_mask] = head[ins_h];
1749
            head[ins_h] = n;
1750
        }
1751
        return Z_OK;
1752
    };
1753
 
1754
    that.deflate = function(_strm, flush) {
1755
        var i, header, level_flags, old_flush, bstate;
1756
 
1757
        if (flush > Z_FINISH || flush < 0) {
1758
            return Z_STREAM_ERROR;
1759
        }
1760
 
1761
        if (!_strm.next_out || (!_strm.next_in && _strm.avail_in !== 0) || (status == FINISH_STATE && flush != Z_FINISH)) {
1762
            _strm.msg = z_errmsg[Z_NEED_DICT - (Z_STREAM_ERROR)];
1763
            return Z_STREAM_ERROR;
1764
        }
1765
        if (_strm.avail_out === 0) {
1766
            _strm.msg = z_errmsg[Z_NEED_DICT - (Z_BUF_ERROR)];
1767
            return Z_BUF_ERROR;
1768
        }
1769
 
1770
        strm = _strm; // just in case
1771
        old_flush = last_flush;
1772
        last_flush = flush;
1773
 
1774
        // Write the zlib header
1775
        if (status == INIT_STATE) {
1776
            header = (Z_DEFLATED + ((w_bits - 8) << 4)) << 8;
1777
            level_flags = ((level - 1) & 0xff) >> 1;
1778
 
1779
            if (level_flags > 3)
1780
                level_flags = 3;
1781
            header |= (level_flags << 6);
1782
            if (strstart !== 0)
1783
                header |= PRESET_DICT;
1784
            header += 31 - (header % 31);
1785
 
1786
            status = BUSY_STATE;
1787
            putShortMSB(header);
1788
        }
1789
 
1790
        // Flush as much pending output as possible
1791
        if (that.pending !== 0) {
1792
            strm.flush_pending();
1793
            if (strm.avail_out === 0) {
1794
                // console.log(" avail_out==0");
1795
                // Since avail_out is 0, deflate will be called again with
1796
                // more output space, but possibly with both pending and
1797
                // avail_in equal to zero. There won't be anything to do,
1798
                // but this is not an error situation so make sure we
1799
                // return OK instead of BUF_ERROR at next call of deflate:
1800
                last_flush = -1;
1801
                return Z_OK;
1802
            }
1803
 
1804
            // Make sure there is something to do and avoid duplicate
1805
            // consecutive
1806
            // flushes. For repeated and useless calls with Z_FINISH, we keep
1807
            // returning Z_STREAM_END instead of Z_BUFF_ERROR.
1808
        } else if (strm.avail_in === 0 && flush <= old_flush && flush != Z_FINISH) {
1809
            strm.msg = z_errmsg[Z_NEED_DICT - (Z_BUF_ERROR)];
1810
            return Z_BUF_ERROR;
1811
        }
1812
 
1813
        // User must not provide more input after the first FINISH:
1814
        if (status == FINISH_STATE && strm.avail_in !== 0) {
1815
            _strm.msg = z_errmsg[Z_NEED_DICT - (Z_BUF_ERROR)];
1816
            return Z_BUF_ERROR;
1817
        }
1818
 
1819
        // Start a new block or continue the current one.
1820
        if (strm.avail_in !== 0 || lookahead !== 0 || (flush != Z_NO_FLUSH && status != FINISH_STATE)) {
1821
            bstate = -1;
1822
            switch (config_table[level].func) {
1823
            case STORED:
1824
                bstate = deflate_stored(flush);
1825
                break;
1826
            case FAST:
1827
                bstate = deflate_fast(flush);
1828
                break;
1829
            case SLOW:
1830
                bstate = deflate_slow(flush);
1831
                break;
1832
            default:
1833
            }
1834
 
1835
            if (bstate == FinishStarted || bstate == FinishDone) {
1836
                status = FINISH_STATE;
1837
            }
1838
            if (bstate == NeedMore || bstate == FinishStarted) {
1839
                if (strm.avail_out === 0) {
1840
                    last_flush = -1; // avoid BUF_ERROR next call, see above
1841
                }
1842
                return Z_OK;
1843
                // If flush != Z_NO_FLUSH && avail_out === 0, the next call
1844
                // of deflate should use the same flush parameter to make sure
1845
                // that the flush is complete. So we don't have to output an
1846
                // empty block here, this will be done at next call. This also
1847
                // ensures that for a very small output buffer, we emit at most
1848
                // one empty block.
1849
            }
1850
 
1851
            if (bstate == BlockDone) {
1852
                if (flush == Z_PARTIAL_FLUSH) {
1853
                    _tr_align();
1854
                } else { // FULL_FLUSH or SYNC_FLUSH
1855
                    _tr_stored_block(0, 0, false);
1856
                    // For a full flush, this empty block will be recognized
1857
                    // as a special marker by inflate_sync().
1858
                    if (flush == Z_FULL_FLUSH) {
1859
                        // state.head[s.hash_size-1]=0;
1860
                        for (i = 0; i < hash_size/*-1*/; i++)
1861
                            // forget history
1862
                            head[i] = 0;
1863
                    }
1864
                }
1865
                strm.flush_pending();
1866
                if (strm.avail_out === 0) {
1867
                    last_flush = -1; // avoid BUF_ERROR at next call, see above
1868
                    return Z_OK;
1869
                }
1870
            }
1871
        }
1872
 
1873
        if (flush != Z_FINISH)
1874
            return Z_OK;
1875
        return Z_STREAM_END;
1876
    };
1877
}
1878
 
1879
// ZStream
1880
 
1881
function ZStream() {
1882
    var that = this;
1883
    that.next_in_index = 0;
1884
    that.next_out_index = 0;
1885
    // that.next_in; // next input byte
1886
    that.avail_in = 0; // number of bytes available at next_in
1887
    that.total_in = 0; // total nb of input bytes read so far
1888
    // that.next_out; // next output byte should be put there
1889
    that.avail_out = 0; // remaining free space at next_out
1890
    that.total_out = 0; // total nb of bytes output so far
1891
    // that.msg;
1892
    // that.dstate;
1893
}
1894
 
1895
ZStream.prototype = {
1896
    deflateInit : function(level, bits) {
1897
        var that = this;
1898
        that.dstate = new Deflate();
1899
        if (!bits)
1900
            bits = MAX_BITS;
1901
        return that.dstate.deflateInit(that, level, bits);
1902
    },
1903
 
1904
    deflate : function(flush) {
1905
        var that = this;
1906
        if (!that.dstate) {
1907
            return Z_STREAM_ERROR;
1908
        }
1909
        return that.dstate.deflate(that, flush);
1910
    },
1911
 
1912
    deflateEnd : function() {
1913
        var that = this;
1914
        if (!that.dstate)
1915
            return Z_STREAM_ERROR;
1916
        var ret = that.dstate.deflateEnd();
1917
        that.dstate = null;
1918
        return ret;
1919
    },
1920
 
1921
    deflateParams : function(level, strategy) {
1922
        var that = this;
1923
        if (!that.dstate)
1924
            return Z_STREAM_ERROR;
1925
        return that.dstate.deflateParams(that, level, strategy);
1926
    },
1927
 
1928
    deflateSetDictionary : function(dictionary, dictLength) {
1929
        var that = this;
1930
        if (!that.dstate)
1931
            return Z_STREAM_ERROR;
1932
        return that.dstate.deflateSetDictionary(that, dictionary, dictLength);
1933
    },
1934
 
1935
    // Read a new buffer from the current input stream, update the
1936
    // total number of bytes read. All deflate() input goes through
1937
    // this function so some applications may wish to modify it to avoid
1938
    // allocating a large strm->next_in buffer and copying from it.
1939
    // (See also flush_pending()).
1940
    read_buf : function(buf, start, size) {
1941
        var that = this;
1942
        var len = that.avail_in;
1943
        if (len > size)
1944
            len = size;
1945
        if (len === 0)
1946
            return 0;
1947
        that.avail_in -= len;
1948
        buf.set(that.next_in.subarray(that.next_in_index, that.next_in_index + len), start);
1949
        that.next_in_index += len;
1950
        that.total_in += len;
1951
        return len;
1952
    },
1953
 
1954
    // Flush as much pending output as possible. All deflate() output goes
1955
    // through this function so some applications may wish to modify it
1956
    // to avoid allocating a large strm->next_out buffer and copying into it.
1957
    // (See also read_buf()).
1958
    flush_pending : function() {
1959
        var that = this;
1960
        var len = that.dstate.pending;
1961
 
1962
        if (len > that.avail_out)
1963
            len = that.avail_out;
1964
        if (len === 0)
1965
            return;
1966
 
1967
        // if (that.dstate.pending_buf.length <= that.dstate.pending_out || that.next_out.length <= that.next_out_index
1968
        // || that.dstate.pending_buf.length < (that.dstate.pending_out + len) || that.next_out.length < (that.next_out_index +
1969
        // len)) {
1970
        // console.log(that.dstate.pending_buf.length + ", " + that.dstate.pending_out + ", " + that.next_out.length + ", " +
1971
        // that.next_out_index + ", " + len);
1972
        // console.log("avail_out=" + that.avail_out);
1973
        // }
1974
 
1975
        that.next_out.set(that.dstate.pending_buf.subarray(that.dstate.pending_out, that.dstate.pending_out + len), that.next_out_index);
1976
 
1977
        that.next_out_index += len;
1978
        that.dstate.pending_out += len;
1979
        that.total_out += len;
1980
        that.avail_out -= len;
1981
        that.dstate.pending -= len;
1982
        if (that.dstate.pending === 0) {
1983
            that.dstate.pending_out = 0;
1984
        }
1985
    }
1986
};
1987
 
1988
// Deflater
1989
 
1990
function Deflater(level) {
1991
    var that = this;
1992
    var z = new ZStream();
1993
    var bufsize = 512;
1994
    var flush = Z_NO_FLUSH;
1995
    var buf = new Uint8Array(bufsize);
1996
 
1997
    if (typeof level == "undefined")
1998
        level = Z_DEFAULT_COMPRESSION;
1999
    z.deflateInit(level);
2000
    z.next_out = buf;
2001
 
2002
    that.append = function(data, onprogress) {
2003
        var err, buffers = [], lastIndex = 0, bufferIndex = 0, bufferSize = 0, array;
2004
        if (!data.length)
2005
            return;
2006
        z.next_in_index = 0;
2007
        z.next_in = data;
2008
        z.avail_in = data.length;
2009
        do {
2010
            z.next_out_index = 0;
2011
            z.avail_out = bufsize;
2012
            err = z.deflate(flush);
2013
            if (err != Z_OK)
2014
                throw "deflating: " + z.msg;
2015
            if (z.next_out_index)
2016
                if (z.next_out_index == bufsize)
2017
                    buffers.push(new Uint8Array(buf));
2018
                else
2019
                    buffers.push(new Uint8Array(buf.subarray(0, z.next_out_index)));
2020
            bufferSize += z.next_out_index;
2021
            if (onprogress && z.next_in_index > 0 && z.next_in_index != lastIndex) {
2022
                onprogress(z.next_in_index);
2023
                lastIndex = z.next_in_index;
2024
            }
2025
        } while (z.avail_in > 0 || z.avail_out === 0);
2026
        array = new Uint8Array(bufferSize);
2027
        buffers.forEach(function(chunk) {
2028
            array.set(chunk, bufferIndex);
2029
            bufferIndex += chunk.length;
2030
        });
2031
        return array;
2032
    };
2033
    that.flush = function() {
2034
        var err, buffers = [], bufferIndex = 0, bufferSize = 0, array;
2035
        do {
2036
            z.next_out_index = 0;
2037
            z.avail_out = bufsize;
2038
            err = z.deflate(Z_FINISH);
2039
            if (err != Z_STREAM_END && err != Z_OK)
2040
                throw "deflating: " + z.msg;
2041
            if (bufsize - z.avail_out > 0)
2042
                buffers.push(new Uint8Array(buf.subarray(0, z.next_out_index)));
2043
            bufferSize += z.next_out_index;
2044
        } while (z.avail_in > 0 || z.avail_out === 0);
2045
        z.deflateEnd();
2046
        array = new Uint8Array(bufferSize);
2047
        buffers.forEach(function(chunk) {
2048
            array.set(chunk, bufferIndex);
2049
            bufferIndex += chunk.length;
2050
        });
2051
        return array;
2052
    };
2053
}