-
Notifications
You must be signed in to change notification settings - Fork 10
/
DeflateStream.hx
2580 lines (2101 loc) · 83.4 KB
/
DeflateStream.hx
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
/*
Copyright (c) 2011, Cameron Desrochers
All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
Certain parts of this file are based on the zlib source.
As such, here is the zlib license in its entirety (from zlib.h):
zlib.h -- interface of the 'zlib' general purpose compression library
version 1.2.5, April 19th, 2010
Copyright (C) 1995-2010 Jean-loup Gailly and Mark Adler
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
Jean-loup Gailly Mark Adler
jloup@gzip.org madler@alumni.caltech.edu
The data format used by the zlib library is described by RFCs (Request for
Comments) 1950 to 1952 in the files http://www.ietf.org/rfc/rfc1950.txt
(zlib format), rfc1951.txt (deflate format) and rfc1952.txt (gzip format).
*/
// This is a zlib/deflate implementation (from scratch!) that was
// created for use by PNGEncoder2, but should be fairly general
// purpose (the API is a bit ungainly though, mostly for
// performance reasons (e.g. no input buffering, assumes
// it's the one using flash.Memory (apart from the client), etc.).
// Tied rather inextricably to the Flash 10+ target (though most
// of the code would port easily to another language that provides
// fast access to raw chunks of memory, like C or C++).
// Some references:
// - RFC 1950 (zlib) and 1951 (DEFLATE)
// - The standard zlib implementation (available from http://zlib.net/)
// - "An Explanation of the Deflate Algorithm" (http://www.zlib.net/feldspar.html)
// - "Length-Limitted Huffman Codes" (http://cbloomrants.blogspot.com/2010/07/07-02-10-length-limitted-huffman-codes.html)
// - "Length-Limitted Huffman Codes Heuristic" (http://cbloomrants.blogspot.com/2010/07/07-03-10-length-limitted-huffman-codes.html)
// - A C implementation of an in-place Huffman code length generator (http://ww2.cs.mu.oz.au/~alistair/inplace.c)
// - FastLZ source: http://fastlz.googlecode.com/svn/trunk/fastlz.c
// - Reverse Parallel algorithm for reversing bits (http://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel)
// - Wikipedia article on canonical Huffman codes (http://en.wikipedia.org/wiki/Canonical_Huffman_code)
// - http://cstheory.stackexchange.com/questions/7420/relation-between-code-length-and-symbol-weight-in-a-huffman-code
// - MurmurHash3: http://code.google.com/p/smhasher/source/browse/trunk/MurmurHash3.cpp
// - Progressive Hashing: http://fastcompression.blogspot.com/2011/10/progressive-hash-series-new-method-to.html
package;
import flash.errors.Error;
import flash.Lib;
import flash.Memory;
import flash.system.ApplicationDomain;
import flash.utils.ByteArray;
import flash.utils.Endian;
enum CompressionLevel {
UNCOMPRESSED; // Fastest
#if !(FAST_ONLY || NORMAL_ONLY || GOOD_ONLY)
FAST; // Huffman coding only
NORMAL; // Huffman + fast LZ77 compression
GOOD; // Huffman + good LZ77 compression
#elseif FAST_ONLY
FAST;
#elseif NORMAL_ONLY
NORMAL;
#elseif GOOD_ONLY
GOOD;
#end
}
// Represents an (offset, end) tuple in domain memory
class MemoryRange {
public var offset : Int;
public var end : Int;
public function new(offset : Int, end : Int)
{
this.offset = offset;
this.end = end;
}
public inline function len() { return end - offset; }
}
// Compliant with RFC 1950 (ZLIB) and RFC 1951 (DEFLATE)
class DeflateStream
{
private static inline var MAX_SYMBOLS_IN_TREE = 286;
private static inline var LENGTH_CODES = 29;
// Minimum number of repeating symbols to use a length/distance pair, according to spec.
// Note that the actual LZ compression code in this file uses a min length of 4 instead.
private static inline var MIN_LENGTH = 3;
private static inline var MAX_LENGTH = 258;
private static inline var LENGTHS = 256;
public static inline var SCRATCH_MEMORY_SIZE : Int = (32 + 19 + MAX_SYMBOLS_IN_TREE * 2 + LENGTHS + MIN_LENGTH + 512) * 4; // Bytes
private static inline var DISTANCE_OFFSET : Int = MAX_SYMBOLS_IN_TREE * 4; // Where distance lookup is stored in scratch memory
private static inline var CODE_LENGTH_OFFSET : Int = DISTANCE_OFFSET + 32 * 4;
private static inline var HUFFMAN_SCRATCH_OFFSET : Int = CODE_LENGTH_OFFSET + 19 * 4;
private static inline var LENGTH_EXTRA_BITS_OFFSET : Int = HUFFMAN_SCRATCH_OFFSET + MAX_SYMBOLS_IN_TREE * 4;
private static inline var DIST_EXTRA_BITS_OFFSET : Int = LENGTH_EXTRA_BITS_OFFSET + (LENGTHS + MIN_LENGTH) * 4;
// Next offset would be at: DIST_EXTRA_BITS_OFFSET + 512 * 4
// FAST compression uses this to decide when to start a new block
private static inline var OUTPUT_BYTES_BEFORE_NEW_BLOCK : Int = 48 * 1024;
// UNCOMPRESSED block sizes must be no more than this many bytes
private static inline var MAX_UNCOMPRESSED_BYTES_PER_BLOCK : UInt = 65535;
// Largest prime smaller than 65536 (see adler32.c in zlib source)
private static inline var ADLER_MAX : Int = 65521;
// Symbols (literal bytes, lengths, and the EOB) must be represented using a
// Huffman code of no more than this many bits for the longest code
private static inline var MAX_CODE_LENGTH : Int = 15;
// The code lengths are serialized using a Huffman code, which must have
// a code length of no more than this many bits
private static inline var MAX_CODE_LENGTH_CODE_LENGTH : Int = 7;
private static inline var EOB = 256; // End of block symbol
private static inline var HASH_SIZE_BITS = 16; // Hash used by NORMAL only
private static inline var HASH_SIZE = 1 << HASH_SIZE_BITS; // # of 4-byte slots in hash
private static inline var HASH_MASK = HASH_SIZE - 1; // Used for fast modulus
private static inline var WINDOW_SIZE = 32768; // Distances must be <= this
private var level : CompressionLevel; // The compression level to use
private var zlib : Bool; // Whether to include zlib (RFC 1951) metadata or not
private var startAddr : UInt; // Where to start writing output bytes
private var currentAddr : Int; // Current (byte) position in output buffer
private var scratchAddr : Int; // Location of scratch memory region
private var blockInProgress : Bool; // Whether a block is currently in progress or not
private var blockStartAddr : Int; // The address that the current block started being output at
private var rangeResult : MemoryRange; // Used when returning a memory range to external clients (avoids spurious small-object allocations)
private var literalLengthCodes : Int; // Count
private var distanceCodes : Int; // Count
// For calculating Adler-32 sum
private var s1 : UInt;
private var s2 : UInt;
// Output is bit-oriented, not byte-oriented. This keeps track of the number of
// bits past the current byte address that the next set of bits should be written to.
private var bitOffset : Int;
// TODO: Add compression ratio (keep track of bits written vs. bits seen)
// Returns a new deflate stream (assumes no other code uses flash.Memory for
// the duration of the lifetime of the stream). No manual memory management
// is required.
public static function create(level : CompressionLevel, writeZLIBInfo = false) : DeflateStream
{
var mem = new ByteArray();
mem.length = ApplicationDomain.MIN_DOMAIN_MEMORY_LENGTH;
Memory.select(mem);
return createEx(level, 0, SCRATCH_MEMORY_SIZE, writeZLIBInfo);
}
// Returns a new deflate stream configured to use pre-selected memory (already
// selected with flash.Memory). The size of the pre-selected memory will
// automatically expand as needed to accomodate the stream as it grows.
// Up to SCRATCH_MEMORY_SIZE bytes will be used at scratchAddr.
// If scratchAddr is past startAddr, then it is the caller's reponsiblity to
// ensure that there's enough room between startAddr and scratchAddr for all of
// the compressed data (thus ensuring that no automatic expansion is needed) --
// use maxOutputBufferSize() to calculate how much space is needed.
public static function createEx(level : CompressionLevel, scratchAddr : Int, startAddr : Int, writeZLIBInfo = false) : DeflateStream
{
return new DeflateStream(level, writeZLIBInfo, scratchAddr, startAddr);
}
private function new(level : CompressionLevel, writeZLIBInfo : Bool, scratchAddr : Int, startAddr : Int)
{
_new(level, writeZLIBInfo, scratchAddr, startAddr);
}
// Code in constructors is slow, so delegate initialization to function
private function _new(level : CompressionLevel, writeZLIBInfo : Bool, scratchAddr : Int, startAddr : Int)
{
fastNew(level, writeZLIBInfo, scratchAddr, startAddr);
}
// Inline initialization (can yield extra performance boost)
private inline function fastNew(level : CompressionLevel, writeZLIBInfo : Bool, scratchAddr : Int, startAddr : Int)
{
this.level = level;
this.zlib = writeZLIBInfo;
this.scratchAddr = scratchAddr;
this.startAddr = startAddr;
this.currentAddr = startAddr;
rangeResult = new MemoryRange(0, 0);
HuffmanTree.scratchAddr = scratchAddr + HUFFMAN_SCRATCH_OFFSET;
// Ensure at least 10 bytes for possible zlib data, block header bits,
// and final empty block.
// writeBits requires up to 3 bytes past what is needed
var mem = ApplicationDomain.currentDomain.domainMemory;
var minLength : UInt = startAddr + 15;
if (mem.length < minLength) {
mem.length = minLength;
Memory.select(mem);
}
distanceCodes = -1;
blockInProgress = false;
blockStartAddr = currentAddr;
bitOffset = 0;
s1 = 1;
s2 = 0;
if (zlib) {
writeByte(0x78); // CMF with compression method 8 (deflate) 32K sliding window
writeByte(0x9C); // FLG: Check bits, no dict, default algorithm
}
setupStaticScratchMem();
// writeBits relies on first byte being initiazed to 0
Memory.setByte(currentAddr, 0);
}
// For best compression, write large chunks of data at once (there
// is no internal buffer for performance reasons)
public function write(bytes : ByteArray)
{
// Put input bytes into fast mem *after* a gap for output bytes.
// This allows multiple calls to update without needing to pre-declare an input
// buffer big enough (i.e. streaming).
var offset = currentAddr + _maxOutputBufferSize(bytes.bytesAvailable);
var end = offset + bytes.bytesAvailable;
// Reserve space
var mem = ApplicationDomain.currentDomain.domainMemory;
var uend : UInt = end;
if (mem.length < uend) {
mem.length = end;
Memory.select(mem);
}
memcpy(bytes, offset);
return fastWrite(offset, end);
}
// Updates the stream with a compressed representation of bytes
// between the from and to indexes (of selected memory).
// For best compression, write large chunks of data at once (there
// is no internal buffering for performance reasons)
public function fastWrite(offset : Int, end : Int)
{
_fastWrite(offset, end);
}
private inline function _fastWrite(offset : Int, end : Int)
{
if (level == UNCOMPRESSED) {
_fastWriteUncompressed(offset, end);
}
else {
_fastWriteCompressed(offset, end);
}
}
// Returns a memory range for the currently written data in the output buffer.
// Guaranteed to always start at the original startAddr passed to createEx.
// Note that the range object returned is owned by the instance, and may change
// after future method calls (but is guaranteed to stay the same until then).
public function peek() : MemoryRange
{
rangeResult.offset = startAddr;
rangeResult.end = currentAddr;
return rangeResult;
}
// Releases all written bytes from the output buffer.
// Use peek() to read the bytes before releasing them.
public function release() : Void
{
if (bitOffset > 0) {
// Copy in-progress byte to start
Memory.setByte(startAddr, Memory.getByte(currentAddr));
}
else {
Memory.setByte(startAddr, 0);
}
// Push back block start so that the distance between currentAddr
// and blockStartAddr remains consistent (it is only used for counting
// the number of bytes in the current block, so an invalid addr is OK)
blockStartAddr = startAddr - (currentAddr - blockStartAddr);
currentAddr = startAddr;
}
// Pre-condition: blockInProgress should always be false
private inline function _fastWriteUncompressed(offset : Int, end : Int)
{
if (zlib) {
updateAdler32(offset, end);
}
// Ensure room to start the blocks and write all data
var blockOverhead = 8; // 1B block header + 4B header + 3B max needed by writeBits
var totalLen : Int = end - offset;
var blocks = Math.ceil(totalLen / MAX_UNCOMPRESSED_BYTES_PER_BLOCK);
var minimumSize : UInt = totalLen + blockOverhead * blocks;
var mem = ApplicationDomain.currentDomain.domainMemory;
var freeSpace : UInt = mem.length - currentAddr;
if (freeSpace < minimumSize) {
mem.length = currentAddr + minimumSize;
Memory.select(mem);
}
while (end - offset > 0) {
var len = Std.int(Math.min(end - offset, MAX_UNCOMPRESSED_BYTES_PER_BLOCK));
beginBlock();
// Write uncompressed header info
writeShort(len);
writeShort(~len);
// Write data (loop unrolled for speed)
var cappedEnd = offset + len;
var cappedEnd32 = offset + (len & 0xFFFFFFE0); // Floor to nearest 32
var i = offset;
while (i < cappedEnd32) {
Memory.setI32(currentAddr, Memory.getI32(i));
Memory.setI32(currentAddr + 4, Memory.getI32(i + 4));
Memory.setI32(currentAddr + 8, Memory.getI32(i + 8));
Memory.setI32(currentAddr + 12, Memory.getI32(i + 12));
Memory.setI32(currentAddr + 16, Memory.getI32(i + 16));
Memory.setI32(currentAddr + 20, Memory.getI32(i + 20));
Memory.setI32(currentAddr + 24, Memory.getI32(i + 24));
Memory.setI32(currentAddr + 28, Memory.getI32(i + 28));
currentAddr += 32;
i += 32;
}
while (i < cappedEnd) {
Memory.setByte(currentAddr, Memory.getByte(i));
++currentAddr;
++i;
}
endBlock();
offset += len;
}
}
private inline function _fastWriteCompressed(offset : Int, end : Int)
{
var len = end - offset;
// Make sure there's enough room in the output
var mem = ApplicationDomain.currentDomain.domainMemory;
var neededLen : UInt = _maxOutputBufferSize(len) + currentAddr;
if (neededLen > mem.length) {
mem.length = _maxOutputBufferSize(len) + currentAddr;
Memory.select(mem);
}
if (zlib) {
updateAdler32(offset, end);
}
#if !(FAST_ONLY || NORMAL_ONLY || GOOD_ONLY)
if (level == FAST) {
_fastWriteFast(offset, end);
}
else if (level == NORMAL) {
_fastWriteNormal(offset, end);
}
else if (level == GOOD) {
_fastWriteGood(offset, end);
}
#elseif FAST_ONLY
if (level == FAST) {
_fastWriteFast(offset, end);
}
#elseif NORMAL_ONLY
if (level == NORMAL) {
_fastWriteNormal(offset, end);
}
#elseif GOOD_ONLY
if (level == GOOD) {
_fastWriteGood(offset, end);
}
#end
else {
throw new Error("Compression level not supported");
}
}
#if (FAST_ONLY || !(FAST_ONLY || NORMAL_ONLY || GOOD_ONLY))
// Uses Huffman coding only (no LZ77 compression)
private inline function _fastWriteFast(offset : Int, end : Int)
{
// Write data in bytesBeforeBlockCheck byte increments -- this allows
// us to efficiently check the current output block size only periodically
var bytesBeforeBlockCheck = 2048;
var i = offset;
var endCheck;
while (end - offset > bytesBeforeBlockCheck) {
endCheck = offset + bytesBeforeBlockCheck;
if (!blockInProgress) {
beginBlock();
// Write Huffman trees into the stream as per RFC 1951
// Estimate bytes (assume ~50% compression ratio)
createAndWriteHuffmanTrees(offset, Std.int(Math.min(end, offset + OUTPUT_BYTES_BEFORE_NEW_BLOCK * 2)));
}
while (i < endCheck) {
// Write data (loop unrolled for speed)
writeSymbol(Memory.getByte(i));
writeSymbol(Memory.getByte(++i));
writeSymbol(Memory.getByte(++i));
writeSymbol(Memory.getByte(++i));
writeSymbol(Memory.getByte(++i));
writeSymbol(Memory.getByte(++i));
writeSymbol(Memory.getByte(++i));
writeSymbol(Memory.getByte(++i));
writeSymbol(Memory.getByte(++i));
writeSymbol(Memory.getByte(++i));
writeSymbol(Memory.getByte(++i));
writeSymbol(Memory.getByte(++i));
writeSymbol(Memory.getByte(++i));
writeSymbol(Memory.getByte(++i));
writeSymbol(Memory.getByte(++i));
writeSymbol(Memory.getByte(++i));
writeSymbol(Memory.getByte(++i));
writeSymbol(Memory.getByte(++i));
writeSymbol(Memory.getByte(++i));
writeSymbol(Memory.getByte(++i));
writeSymbol(Memory.getByte(++i));
writeSymbol(Memory.getByte(++i));
writeSymbol(Memory.getByte(++i));
writeSymbol(Memory.getByte(++i));
writeSymbol(Memory.getByte(++i));
writeSymbol(Memory.getByte(++i));
writeSymbol(Memory.getByte(++i));
writeSymbol(Memory.getByte(++i));
writeSymbol(Memory.getByte(++i));
writeSymbol(Memory.getByte(++i));
writeSymbol(Memory.getByte(++i));
writeSymbol(Memory.getByte(++i));
++i;
}
offset += bytesBeforeBlockCheck;
if (currentBlockLength() > OUTPUT_BYTES_BEFORE_NEW_BLOCK) {
endBlock();
}
}
if (i < end) {
if (!blockInProgress) {
beginBlock();
createAndWriteHuffmanTrees(offset, end);
}
while (i < end) {
writeSymbol(Memory.getByte(i));
++i;
}
if (currentBlockLength() > OUTPUT_BYTES_BEFORE_NEW_BLOCK) {
endBlock();
}
}
}
#end
#if (NORMAL_ONLY || !(FAST_ONLY || NORMAL_ONLY || GOOD_ONLY))
// Uses a quick version of LZ77 compression, and Huffman coding
private inline function _fastWriteNormal(offset : Int, end : Int)
{
var cappedEnd, safeEnd;
var symbol;
var length;
var lengthInfo;
var distance;
var distanceInfo;
var hashOffset;
var i, j, k;
// i: The current index into the input buffer
// j: The lookahead index into the input buffer, starting at a hash entry
// k: The lookahead index into the input buffer, starting at i
// blockInProgress should always be false here
// Instead of writing symbols directly to output stream, write them
// to a temporary buffer instead. This lets us compute exact symbol
// likelihood statistics for creating the Huffman trees, which are
// then used to encode the buffer into the final output stream.
// Symbols in the temporary buffer are all two-bytes, and can be literals
// or lengths. Lengths are represented by 512 + the actual length value.
// Lengths are immediately followed by a two-byte distance (actual value).
// The hash holds indexes to the input buffer -- the hash code is calculated
// based on the first four bytes at that index. So, to check if a given
// string starting with a certain four bytes has been seen before, you
// can simply hash the first 4 bytes and look it up in the hash, then find
// the match length. Note that collisions are "resolved" just by replacing
// the old value with the new one (i.e., no collision resolution). This is
// done for speed. The hash is updated for every input byte, except the ones
// within a match (however, the first and last bytes of the match are inserted).
var hashAddr = currentAddr + _maxOutputBufferSize(end - offset) - HASH_SIZE * 4;
var bufferAddr = hashAddr - OUTPUT_BYTES_BEFORE_NEW_BLOCK * 2 * 2;
var currentBufferAddr;
// Initialize hash table to invalid data (HASH_SIZE is divisble by 8)
i = hashAddr + HASH_SIZE * 4 - 32;
while (i >= hashAddr) {
Memory.setI32(i, -1);
Memory.setI32(i + 4, -1);
Memory.setI32(i + 8, -1);
Memory.setI32(i + 12, -1);
Memory.setI32(i + 16, -1);
Memory.setI32(i + 20, -1);
Memory.setI32(i + 24, -1);
Memory.setI32(i + 28, -1);
i -= 32;
}
while (end - offset > 0) {
// Assume ~50% compression ratio
cappedEnd = Std.int(Math.min(end, offset + OUTPUT_BYTES_BEFORE_NEW_BLOCK * 2));
safeEnd = cappedEnd - 4; // Can read up to 4 ahead without worrying
// Phase 1: Use LZ77 compression to determine literals, lengths, and distances to
// later be encoded. Put these in a temporary output buffer, and track the frequency
// of each symbol
clearSymbolFrequencies();
currentBufferAddr = bufferAddr;
i = offset;
while (i < safeEnd) {
hashOffset = LZHash.hash4(i, HASH_MASK) << 2; // Multiply by 4 since each entry is 4 bytes
j = Memory.getI32(hashAddr + hashOffset); // Index from hash
if (j >= 0 && Memory.getI32(j) == Memory.getI32(i)) {
// Hash value was valid and first 4 bytes match!
// Find length of match
length = 4;
j += 4;
k = i + 4;
while (k < cappedEnd && Memory.getByte(j) == Memory.getByte(k) && length < MAX_LENGTH) {
++j;
++k;
++length;
}
// Update hash before incrementing
Memory.setI32(hashAddr + hashOffset, i);
distance = k - j;
if (distance <= WINDOW_SIZE) {
incSymbolFrequency(Memory.getUI16(scratchAddr + LENGTH_EXTRA_BITS_OFFSET + (length << 2) + 2));
distanceInfo = getDistanceInfo(distance);
incSymbolFrequency(distanceInfo >>> 24, DISTANCE_OFFSET);
Memory.setI32(currentBufferAddr, (length | 512) | (distance << 16));
currentBufferAddr += 4;
i += length;
if (i < safeEnd) {
// Update hash after
Memory.setI32(hashAddr + (LZHash.hash4(i - 1, HASH_MASK) << 2), i - 1);
}
}
else { // Match, but distance too far -- output literal
symbol = Memory.getByte(i);
Memory.setI16(currentBufferAddr, symbol);
incSymbolFrequency(symbol);
currentBufferAddr += 2;
++i;
}
}
else {
// No luck with hash table. Output literal:
symbol = Memory.getByte(i);
Memory.setI16(currentBufferAddr, symbol);
incSymbolFrequency(symbol);
Memory.setI32(hashAddr + hashOffset, i);
currentBufferAddr += 2;
++i;
}
}
// Output remaining literals without hash table
while (i < cappedEnd) {
symbol = Memory.getByte(i);
Memory.setI16(currentBufferAddr, symbol);
incSymbolFrequency(symbol);
currentBufferAddr += 2;
++i;
}
// Phase 2: Encode buffered data to output stream
beginBlock();
createAndWriteHuffmanTrees(offset, cappedEnd);
i = bufferAddr;
while (i + 64 <= currentBufferAddr) { // Up to 16 length/distance pairs, or 32 literals
symbol = writeTemporaryBufferSymbol(i);
i += 2 + ((symbol & 512) >>> 8);
symbol = writeTemporaryBufferSymbol(i);
i += 2 + ((symbol & 512) >>> 8);
symbol = writeTemporaryBufferSymbol(i);
i += 2 + ((symbol & 512) >>> 8);
symbol = writeTemporaryBufferSymbol(i);
i += 2 + ((symbol & 512) >>> 8);
symbol = writeTemporaryBufferSymbol(i);
i += 2 + ((symbol & 512) >>> 8);
symbol = writeTemporaryBufferSymbol(i);
i += 2 + ((symbol & 512) >>> 8);
symbol = writeTemporaryBufferSymbol(i);
i += 2 + ((symbol & 512) >>> 8);
symbol = writeTemporaryBufferSymbol(i);
i += 2 + ((symbol & 512) >>> 8);
symbol = writeTemporaryBufferSymbol(i);
i += 2 + ((symbol & 512) >>> 8);
symbol = writeTemporaryBufferSymbol(i);
i += 2 + ((symbol & 512) >>> 8);
symbol = writeTemporaryBufferSymbol(i);
i += 2 + ((symbol & 512) >>> 8);
symbol = writeTemporaryBufferSymbol(i);
i += 2 + ((symbol & 512) >>> 8);
symbol = writeTemporaryBufferSymbol(i);
i += 2 + ((symbol & 512) >>> 8);
symbol = writeTemporaryBufferSymbol(i);
i += 2 + ((symbol & 512) >>> 8);
symbol = writeTemporaryBufferSymbol(i);
i += 2 + ((symbol & 512) >>> 8);
symbol = writeTemporaryBufferSymbol(i);
i += 2 + ((symbol & 512) >>> 8);
}
while (i < currentBufferAddr) {
symbol = writeTemporaryBufferSymbol(i);
i += 2 + ((symbol & 512) >>> 8);
}
endBlock();
offset = cappedEnd;
}
}
#end
#if (GOOD_ONLY || !(FAST_ONLY || NORMAL_ONLY || GOOD_ONLY))
private inline function _fastWriteGood(offset : Int, end : Int)
{
var cappedEnd, maxMatchEnd, lookaheadEnd;
var symbol;
var length, lengthInfo;
var distanceInfo;
var hashOffset;
var i, j, k;
// Works just like _fastWriteNormal, but uses a different hash (LZHash)
var hashAddr = currentAddr + _maxOutputBufferSize(end - offset) - LZHash.MEMORY_SIZE;
var bufferAddr = hashAddr - OUTPUT_BYTES_BEFORE_NEW_BLOCK * 2 * 2;
var currentBufferAddr;
var hash = new LZHash(hashAddr, MAX_LENGTH, WINDOW_SIZE);
while (end - offset > 0) {
// Assume ~50% compression ratio
cappedEnd = Std.int(Math.min(end, offset + OUTPUT_BYTES_BEFORE_NEW_BLOCK * 2));
lookaheadEnd = cappedEnd - LZHash.MAX_LOOKAHEAD;
maxMatchEnd = lookaheadEnd - (MAX_LENGTH << 1) - 1;
// Phase 1: Use LZ77 compression to determine literals, lengths, and distances to
// later be encoded. Put these in a temporary output buffer, and track the frequency
// of each symbol
clearSymbolFrequencies();
currentBufferAddr = bufferAddr;
i = offset;
// Note that if this if (or else if) are not entered, we
// cannot call the searchAndUpdate method, but we won't since
// the next two loops will never be entered
if (i < maxMatchEnd) {
hash.unsafeInitLookahead(offset);
}
else if (i < lookaheadEnd) {
hash.initLookahead(offset, cappedEnd);
}
while (i < maxMatchEnd) {
hash.unsafeSearchAndUpdate(i);
if (Memory.getUI16(hash.resultAddr) >= LZHash.MIN_MATCH_LENGTH) {
length = Memory.getUI16(hash.resultAddr);
incSymbolFrequency(Memory.getUI16(scratchAddr + LENGTH_EXTRA_BITS_OFFSET + (length << 2) + 2));
distanceInfo = getDistanceInfo(Memory.getUI16(hash.resultAddr + 2));
incSymbolFrequency(distanceInfo >>> 24, DISTANCE_OFFSET);
Memory.setI32(currentBufferAddr, Memory.getI32(hash.resultAddr) | 512);
currentBufferAddr += 4;
i += length;
}
else {
// No luck with hash table. Output literal:
symbol = Memory.getByte(i);
Memory.setI16(currentBufferAddr, symbol);
incSymbolFrequency(symbol);
currentBufferAddr += 2;
++i;
}
}
while (i < lookaheadEnd) {
hash.searchAndUpdate(i, cappedEnd);
if (Memory.getUI16(hash.resultAddr) >= LZHash.MIN_MATCH_LENGTH) {
length = Memory.getUI16(hash.resultAddr);
incSymbolFrequency(Memory.getUI16(scratchAddr + LENGTH_EXTRA_BITS_OFFSET + (length << 2) + 2));
distanceInfo = getDistanceInfo(Memory.getUI16(hash.resultAddr + 2));
incSymbolFrequency(distanceInfo >>> 24, DISTANCE_OFFSET);
Memory.setI32(currentBufferAddr, Memory.getI32(hash.resultAddr) | 512);
currentBufferAddr += 4;
i += length;
}
else {
// No luck with hash table. Output literal:
symbol = Memory.getByte(i);
Memory.setI16(currentBufferAddr, symbol);
incSymbolFrequency(symbol);
currentBufferAddr += 2;
++i;
}
}
while (i < cappedEnd) {
symbol = Memory.getByte(i);
Memory.setI16(currentBufferAddr, symbol);
incSymbolFrequency(symbol);
currentBufferAddr += 2;
++i;
}
// Phase 2: Encode buffered data to output stream
beginBlock();
createAndWriteHuffmanTrees(offset, cappedEnd);
i = bufferAddr;
while (i + 64 <= currentBufferAddr) { // Up to 16 length/distance pairs, or 32 literals
symbol = writeTemporaryBufferSymbol(i);
i += 2 + ((symbol & 512) >>> 8);
symbol = writeTemporaryBufferSymbol(i);
i += 2 + ((symbol & 512) >>> 8);
symbol = writeTemporaryBufferSymbol(i);
i += 2 + ((symbol & 512) >>> 8);
symbol = writeTemporaryBufferSymbol(i);
i += 2 + ((symbol & 512) >>> 8);
symbol = writeTemporaryBufferSymbol(i);
i += 2 + ((symbol & 512) >>> 8);
symbol = writeTemporaryBufferSymbol(i);
i += 2 + ((symbol & 512) >>> 8);
symbol = writeTemporaryBufferSymbol(i);
i += 2 + ((symbol & 512) >>> 8);
symbol = writeTemporaryBufferSymbol(i);
i += 2 + ((symbol & 512) >>> 8);
symbol = writeTemporaryBufferSymbol(i);
i += 2 + ((symbol & 512) >>> 8);
symbol = writeTemporaryBufferSymbol(i);
i += 2 + ((symbol & 512) >>> 8);
symbol = writeTemporaryBufferSymbol(i);
i += 2 + ((symbol & 512) >>> 8);
symbol = writeTemporaryBufferSymbol(i);
i += 2 + ((symbol & 512) >>> 8);
symbol = writeTemporaryBufferSymbol(i);
i += 2 + ((symbol & 512) >>> 8);
symbol = writeTemporaryBufferSymbol(i);
i += 2 + ((symbol & 512) >>> 8);
symbol = writeTemporaryBufferSymbol(i);
i += 2 + ((symbol & 512) >>> 8);
symbol = writeTemporaryBufferSymbol(i);
i += 2 + ((symbol & 512) >>> 8);
}
while (i < currentBufferAddr) {
symbol = writeTemporaryBufferSymbol(i);
i += 2 + ((symbol & 512) >>> 8);
}
endBlock();
offset = cappedEnd;
}
}
#end
#if !FAST_ONLY
private inline function writeTemporaryBufferSymbol(i : Int) : Int
{
var length, distance, lengthInfo, distanceInfo;
var symbol = Memory.getUI16(i);
if ((symbol & 512) != 0) {
// Length/distance pair
length = symbol ^ 512;
lengthInfo = Memory.getI32(scratchAddr + LENGTH_EXTRA_BITS_OFFSET + (length << 2));
writeSymbol(lengthInfo >>> 16);
writeBits(length - (lengthInfo & 0x1FFF), (lengthInfo & 0xFF00) >>> 13);
distance = Memory.getUI16(i + 2);
distanceInfo = getDistanceInfo(distance);
writeSymbol(distanceInfo >>> 24, DISTANCE_OFFSET);
writeBits(distance - (distanceInfo & 0xFFFF), (distanceInfo & 0xFF0000) >>> 16);
}
else {
// Literal
writeSymbol(symbol);
}
return symbol;
}
#end
private inline function beginBlock(lastBlock = false)
{
blockInProgress = true;
if (level == CompressionLevel.UNCOMPRESSED) {
if (bitOffset == 0) {
// Current output is aligned to byte, indicating
// last write may not have been made using writeBits;
// writeBits requires that next byte be zero
Memory.setByte(currentAddr, 0);
}
// Write BFINAL bit and BTYPE (00)
writeBits(lastBlock ? 1 : 0, 3); // Uncompressed
// Align to byte boundary
if (bitOffset > 0) {
writeBits(0, 8 - bitOffset);
}
}
else {
writeBits(4 | (lastBlock ? 1 : 0), 3); // Dynamic Huffman tree compression
}
blockStartAddr = currentAddr;
}
// Call only once. After called, no other methods should be called
public function finalize() : ByteArray
{
var range = fastFinalize();
var result = new ByteArray();
if (zlib) {
result.endian = BIG_ENDIAN; // Network byte order (RFC 1950)
}
else {
result.endian = LITTLE_ENDIAN;
}
var mem = ApplicationDomain.currentDomain.domainMemory;
mem.position = range.offset;
mem.readBytes(result, 0, range.len());
result.position = 0;
return result;
}
// Call only once. After called, no other methods should be called
public function fastFinalize() : MemoryRange
{
if (blockInProgress) {
endBlock();
}
// It's easier to always write one empty block at the end than to force
// the caller to know in advance which block is the last one.
writeEmptyBlock(true);
// Align to byte boundary
if (bitOffset > 0) {
++currentAddr; // active byte is now last byte
}
if (zlib) {
// Write Adler-32 sum in big endian order
// adlerSum = (s2 << 16) | s1;
writeByte(s2 >>> 8);
writeByte(s2);
writeByte(s1 >>> 8);
writeByte(s1);
}
rangeResult.offset = startAddr;
rangeResult.end = currentAddr;
return rangeResult;
}