-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathUraniumCompressJS.js
2140 lines (1964 loc) · 76 KB
/
UraniumCompressJS.js
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
/*
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
*/
var RangeCoder //no dependencies
, Stream //no dependencies
, BitStream //depands on [Stream]
, Util //depands on [Stream]
, LogDistanceModel //depands on [Util(Stream)]
, Huffman //depands on [Util(Stream),BitStream(Stream)]
, NoModel //depands on [Util(Stream),BitStream(Stream)]
, FenwickModel //depands on [RangeCoder, Stream, Util(Stream)]
, Context1Model //depands on [Util(Stream),BitStream(Stream),Huffman(Util(Stream),BitStream(Stream))]
, LzjbR //depands on [RangeCoder, Stream, Util(Stream), LogDistanceModel(Util(Stream)), NoModel(Util(Stream),BitStream(Stream)), FenwickModel(RangeCoder, Stream, Util(Stream)), Context1Model(Util(Stream),BitStream(Stream),Huffman(Util(Stream),BitStream(Stream)))
, Lzp3;
RangeCoder = function () {
/* Range Coder. Inspired by rangecod.c from rngcod13.zip from
* http://www.compressconsult.com/rangecoder/
* This JavaScript version is:
* Copyright (c) 2013 C. Scott Ananian.
*/
// Uses 32-bit integer math. Hopefully the JavaScript runtime figures
// that out. ;)
// see https://github.com/kripken/emscripten/wiki/LLVM-Types-in-JavaScript
// for some hints on doing 32-bit unsigned match in JavaScript.
// One key is the use of ">>>0" to change a signed result to unsigned.
var IMUL = Math.imul;
var CODE_BITS = 32;
var Top_value = Math.pow(2, CODE_BITS - 1);
var SHIFT_BITS = CODE_BITS - 9;
var EXTRA_BITS = (CODE_BITS - 2) % 8 + 1;
var Bottom_value = Top_value >>> 8;
var MAX_INT = Math.pow(2, CODE_BITS) - 1;
/* it is highly recommended that the total frequency count is less */
/* than 1 << 19 to minimize rounding effects. */
/* the total frequency count MUST be less than 1<<23 */
var RangeCoder = function RangeCoder(stream) {
this.low = 0; /* low end of interval */
this.range = Top_value; /* length of interval */
this.buffer = 0; /* buffer for input/output */
this.help = 0; /* bytes_to_follow / intermediate value */
this.bytecount = 0; /* counter for output bytes */
this.stream = stream;
};
/* Do the normalization before we need a defined state, instead of
* after messing it up. This simplifies starting and ending. */
var enc_normalize = function enc_normalize(rc, outputStream) {
while (rc.range <= Bottom_value) {
/* do we need renormalization? */
if (rc.low < 0xFF << SHIFT_BITS) {
//no carry possible, so output
outputStream.writeByte(rc.buffer);
for (; rc.help; rc.help--) outputStream.writeByte(0xFF);
rc.buffer = rc.low >>> SHIFT_BITS & 0xFF;
} else if (rc.low & Top_value) {
/* carry now, no future carry */
outputStream.writeByte(rc.buffer + 1);
for (; rc.help; rc.help--) outputStream.writeByte(0x00);
rc.buffer = rc.low >>> SHIFT_BITS & 0xFF;
} else {
rc.help++;
if (rc.help > MAX_INT) throw new Error("Too many bytes outstanding, " + "file too large!");
}
rc.range = rc.range << 8 >>> 0; /*ensure result remains positive*/
rc.low = (rc.low << 8 & Top_value - 1) >>> 0; /* unsigned */
rc.bytecount++;
}
};
/* Start the encoder */
/* c is written as the first byte in the datastream.
* one could do w/o, but then you have an additional if per output byte */
RangeCoder.prototype.encodeStart = function (c, initlength) {
this.low = 0;
this.range = Top_value;
this.buffer = c;
this.help = 0;
this.bytecount = initlength;
};
/* Encode a symbol using frequencies */
/* rc is the range coder to be used */
/* sy_f is the interval length (frequency of the symbol) */
/* lt_f is the lower end (frequency sum of < symbols) */
/* tot_f is the total interval length (total frequency sum) */
/* or (faster): tot_f = (code_value)1<<shift */
RangeCoder.prototype.encodeFreq = function (sy_f, lt_f, tot_f) {
enc_normalize(this, this.stream);
var r = this.range / tot_f >>> 0; // note coercion to integer
var tmp = IMUL(r, lt_f);
this.low += tmp;
if (lt_f + sy_f < tot_f) {
this.range = IMUL(r, sy_f);
} else {
this.range -= tmp;
}
};
RangeCoder.prototype.encodeShift = function (sy_f, lt_f, shift) {
enc_normalize(this, this.stream);
var r = this.range >>> shift;
var tmp = IMUL(r, lt_f);
this.low += tmp;
if (lt_f + sy_f >>> shift) {
this.range -= tmp;
} else {
this.range = IMUL(r, sy_f);
}
};
/* Encode a bit w/o modelling. */
RangeCoder.prototype.encodeBit = function (b) {
this.encodeShift(1, b ? 1 : 0, 1);
};
/* Encode a byte w/o modelling. */
RangeCoder.prototype.encodeByte = function (b) {
this.encodeShift(1, b, 8);
};
/* Encode a short w/o modelling. */
RangeCoder.prototype.encodeShort = function (s) {
this.encodeShift(1, s, 16);
};
/* Finish encoding */
/* returns number of bytes written */
RangeCoder.prototype.encodeFinish = function () {
var outputStream = this.stream;
enc_normalize(this, outputStream);
this.bytecount += 5;
var tmp = this.low >>> SHIFT_BITS;
if ((this.low & Bottom_value - 1) >= (this.bytecount & 0xFFFFFF) >>> 1) {
tmp++;
}
if (tmp > 0xFF) {
/* we have a carry */
outputStream.writeByte(this.buffer + 1);
for (; this.help; this.help--) outputStream.writeByte(0x00);
} else {
/* no carry */
outputStream.writeByte(this.buffer);
for (; this.help; this.help--) outputStream.writeByte(0xFF);
}
outputStream.writeByte(tmp & 0xFF);
// XXX: i'm pretty sure these could be three arbitrary bytes
// they are consumed by the decoder at the end
outputStream.writeByte(this.bytecount >>> 16 & 0xFF);
outputStream.writeByte(this.bytecount >>> 8 & 0xFF);
outputStream.writeByte(this.bytecount & 0xFF);
return this.bytecount;
};
/* Start the decoder; you need to provide the *second* byte from the
* datastream. (The first byte was provided to startEncoding and is
* ignored by the decoder.)
*/
RangeCoder.prototype.decodeStart = function (skipInitialRead) {
var c = skipInitialRead ? 0 : this.stream.readByte();
if (typeof c !== 'number' || c < 0) {
return c; // EOF
}
this.buffer = this.stream.readByte();
this.low = this.buffer >>> 8 - EXTRA_BITS;
this.range = 1 << EXTRA_BITS;
return c;
};
var dec_normalize = function dec_normalize(rc, inputStream) {
while (rc.range <= Bottom_value) {
rc.low = rc.low << 8 | rc.buffer << EXTRA_BITS & 0xFF;
/* rc.low could be negative here; don't fix it quite yet */
rc.buffer = inputStream.readByte();
rc.low |= rc.buffer >>> 8 - EXTRA_BITS;
rc.low = rc.low >>> 0; /* fix it now */
rc.range = rc.range << 8 >>> 0; /* ensure stays positive */
}
};
/* Calculate cumulative frequency for next symbol. Does NO update!*/
/* rc is the range coder to be used */
/* tot_f is the total frequency */
/* or: totf is (code_value)1<<shift */
/* returns the <= cumulative frequency */
RangeCoder.prototype.decodeCulFreq = function (tot_f) {
dec_normalize(this, this.stream);
this.help = this.range / tot_f >>> 0; // note coercion to integer
var tmp = this.low / this.help >>> 0; // again
return tmp >= tot_f ? tot_f - 1 : tmp;
};
RangeCoder.prototype.decodeCulShift = function (shift) {
dec_normalize(this, this.stream);
this.help = this.range >>> shift;
var tmp = this.low / this.help >>> 0; // coercion to unsigned
// shift is less than 31, so shift below will remain positive
return tmp >>> shift ? (1 << shift) - 1 : tmp;
};
/* Update decoding state */
/* rc is the range coder to be used */
/* sy_f is the interval length (frequency of the symbol) */
/* lt_f is the lower end (frequency sum of < symbols) */
/* tot_f is the total interval length (total frequency sum) */
RangeCoder.prototype.decodeUpdate = function (sy_f, lt_f, tot_f) {
var tmp = this.help * lt_f; // should not overflow!
this.low -= tmp;
if (lt_f + sy_f < tot_f) {
this.range = this.help * sy_f;
} else {
this.range -= tmp;
}
};
/* Decode a bit w/o modelling. */
RangeCoder.prototype.decodeBit = function () {
var tmp = this.decodeCulShift(1);
this.decodeUpdate(1, tmp, 1 << 1);
return tmp;
};
/* decode a byte w/o modelling */
RangeCoder.prototype.decodeByte = function () {
var tmp = this.decodeCulShift(8);
this.decodeUpdate(1, tmp, 1 << 8);
return tmp;
};
/* decode a short w/o modelling */
RangeCoder.prototype.decodeShort = function () {
var tmp = this.decodeCulShift(16);
this.decodeUpdate(1, tmp, 1 << 16);
return tmp;
};
/* Finish decoding */
RangeCoder.prototype.decodeFinish = function () {
/* normalize to use up all bytes */
dec_normalize(this, this.stream);
};
/** Utility functions */
// bitstream interface
RangeCoder.prototype.writeBit = RangeCoder.prototype.encodeBit;
RangeCoder.prototype.readBit = RangeCoder.prototype.decodeBit;
// stream interface
RangeCoder.prototype.writeByte = RangeCoder.prototype.encodeByte;
RangeCoder.prototype.readByte = RangeCoder.prototype.decodeByte;
return RangeCoder;
}();
Stream = function () {
/** Abstract Stream interface, for byte-oriented i/o. */
var EOF = -1;
var Stream = function Stream() {
/* ABSTRACT */
};
// you must define one of read / readByte for a readable stream
Stream.prototype.readByte = function () {
var buf = [0];
var len = this.read(buf, 0, 1);
if (len === 0) {
this._eof = true;
return EOF;
}
return buf[0];
};
Stream.prototype.read = function (buf, bufOffset, length) {
var ch,
bytesRead = 0;
while (bytesRead < length) {
ch = this.readByte();
if (ch === EOF) {
this._eof = true;
break;
}
buf[bufOffset + bytesRead++] = ch;
}
return bytesRead;
};
Stream.prototype.eof = function () {
return !!this._eof;
}; // reasonable default implementation of 'eof'
Stream.prototype.seek = function (pos) {
// not all readable streams are seekable
throw new Error('Stream is not seekable.');
};
Stream.prototype.tell = function () {
throw new Error('Stream is not seekable.');
};
Stream.prototype.writeByte = function (_byte) {
// you must define one of write / writeByte for a writable stream
var buf = [_byte];
this.write(buf, 0, 1);
};
Stream.prototype.write = function (buf, bufOffset, length) {
var i;
for (i = 0; i < length; i=i+1|0) {
this.writeByte(buf[bufOffset + i]);
}
return length;
};
Stream.prototype.flush = function () {}; //flush will happily do nothing if you don't override it.
Stream.EOF = EOF; //export EOF as a varant.
return Stream;
}();
BitStream = function () {
/** Big-Endian Bit Stream, implemented on top of a (normal byte) stream. */
var BitStream = function BitStream(stream) {
(function () {
var bufferByte = 0x100; // private var for readers
this.readBit = function () {
if ((bufferByte & 0xFF) === 0) {
var ch = stream.readByte();
if (ch === Stream.EOF) {
this._eof = true;
return ch; /* !!! */
}
bufferByte = ch << 1 | 1;
}
var bit = bufferByte & 0x100 ? 1 : 0;
bufferByte <<= 1;
return bit;
};
// implement byte stream interface as well.
this.readByte = function () {
if ((bufferByte & 0xFF) === 0) {
return stream.readByte();
}
return this.readBits(8);
};
this.seek = function (pos) {
stream.seek(pos);
bufferByte = 0x100;
};
}).call(this);
(function () {
var bufferByte = 1; // private var for writers
this.writeBit = function (b) {
bufferByte <<= 1;
if (b) {
bufferByte |= 1;
}
if (bufferByte & 0x100) {
stream.writeByte(bufferByte & 0xFF);
bufferByte = 1;
}
};
// implement byte stream interface as well
this.writeByte = function (_byte) {
if (bufferByte === 1) {
stream.writeByte(_byte);
} else {
stream.writeBits(8, _byte);
}
};
this.flush = function () {
while (bufferByte !== 1) {
this.writeBit(0);
}
if (stream.flush) {
stream.flush();
}
};
}).call(this);
};
// inherit read/write methods from Stream.
BitStream.EOF = Stream.EOF;
BitStream.prototype = Object.create(Stream.prototype);
// bit chunk read/write
BitStream.prototype.readBits = function (n) {
var i,
r = 0,
b;
if (n > 31) {
r = this.readBits(n - 16) * 0x10000; // fp multiply, not shift
return r + this.readBits(16);
}
for (i = 0; i < n; i=i+1|0) {
r <<= 1; // this could make a negative value if n>31
// bits read past EOF are all zeros!
if (this.readBit() > 0) {
r++;
}
}
return r;
};
BitStream.prototype.writeBits = function (n, value) {
if (n > 32) {
var low = value & 0xFFFF;
var high = (value - low) / 0x10000; // fp division, not shift
this.writeBits(n - 16, high);
this.writeBits(16, low);
return;
}
var i;
for (i = n - 1; i >= 0; i=i-1|0) {
this.writeBit(value >>> i & 1);
}
};
return BitStream;
}();
Util = function () {
var Util = Object.create(null);
var EOF = Stream.EOF;
/* Take a buffer, array, or stream, and return an input stream. */
Util.coerceInputStream = function (input, forceRead) {
if (!('readByte' in input)) {
var buffer = input;
input = new Stream();
input.size = buffer.length;
input.pos = 0;
input.readByte = function () {
if (this.pos >= this.size) {
return EOF;
}
return buffer[this.pos++];
};
input.read = function (buf, bufOffset, length) {
var bytesRead = 0;
while (bytesRead < length && this.pos < buffer.length) {
buf[bufOffset++] = buffer[this.pos++];
bytesRead++;
}
return bytesRead;
};
input.seek = function (pos) {
this.pos = pos;
};
input.tell = function () {
return this.pos;
};
input.eof = function () {
return this.pos >= buffer.length;
};
} else if (forceRead && !('read' in input)) {
// wrap input if it doesn't implement read
var s = input;
input = new Stream();
input.readByte = function () {
var ch = s.readByte();
if (ch === EOF) {
this._eof = true;
}
return ch;
};
if ('size' in s) {
input.size = s.size;
}
if ('seek' in s) {
input.seek = function (pos) {
s.seek(pos); // may throw if s doesn't implement seek
this._eof = false;
};
}
if ('tell' in s) {
input.tell = s.tell.bind(s);
}
}
return input;
};
var BufferStream = function BufferStream(buffer, resizeOk) {
this.buffer = buffer;
this.resizeOk = resizeOk;
this.pos = 0;
};
BufferStream.prototype = Object.create(Stream.prototype);
BufferStream.prototype.writeByte = function (_byte) {
if (this.resizeOk && this.pos >= this.buffer.length) {
var newBuffer = Util.makeU8Buffer(this.buffer.length * 2);
newBuffer.set(this.buffer);
this.buffer = newBuffer;
}
this.buffer[this.pos++] = _byte;
};
BufferStream.prototype.getBuffer = function () {
// trim buffer if needed
if (this.pos !== this.buffer.length) {
if (!this.resizeOk) throw new TypeError('outputsize does not match decoded input');
var newBuffer = Util.makeU8Buffer(this.pos);
newBuffer.set(this.buffer.subarray(0, this.pos));
this.buffer = newBuffer;
}
return this.buffer;
};
/* Take a stream (or not) and an (optional) size, and return an
* output stream. Return an object with a 'retval' field equal to
* the output stream (if that was given) or else a pointer at the
* internal Uint8Array/buffer/array; and a 'stream' field equal to
* an output stream to use.
*/
Util.coerceOutputStream = function (output, size) {
var r = {
stream: output,
retval: output
};
if (output) {
if (typeof output === 'object' && 'writeByte' in output) {
return r; /* leave output alone */
} else if (typeof size === 'number') {
r.stream = new BufferStream(Util.makeU8Buffer(size), false);
} else {
// output is a buffer
r.stream = new BufferStream(output, false);
}
} else {
r.stream = new BufferStream(Util.makeU8Buffer(16384), true);
}
Object.defineProperty(r, 'retval', {
get: r.stream.getBuffer.bind(r.stream)
});
return r;
};
Util.compressFileHelper = function (magic, guts, suppressFinalByte) {
return function (inStream, outStream, props) {
inStream = Util.coerceInputStream(inStream);
var o = Util.coerceOutputStream(outStream, outStream);
outStream = o.stream;
// write the magic number to identify this file type
// (it better be ASCII, we're not doing utf-8 conversion)
var i;
for (i = 0; i < magic.length; i=i+1|0) {
outStream.writeByte(magic.charCodeAt(i));
}
// if we know the size, write it
var fileSize;
if ('size' in inStream && inStream.size >= 0) {
fileSize = inStream.size;
} else {
fileSize = -1; // size unknown
}
if (suppressFinalByte) {
var tmpOutput = Util.coerceOutputStream([]);
Util.writeUnsignedNumber(tmpOutput.stream, fileSize + 1);
tmpOutput = tmpOutput.retval;
for (i = 0; i < tmpOutput.length - 1; i=i+1|0) {
outStream.writeByte(tmpOutput[i]);
}
suppressFinalByte = tmpOutput[tmpOutput.length - 1];
} else {
Util.writeUnsignedNumber(outStream, fileSize + 1);
}
// call the guts to do the real compression
guts(inStream, outStream, fileSize, props, suppressFinalByte);
return o.retval;
};
};
Util.decompressFileHelper = function (magic, guts) {
return function (inStream, outStream) {
inStream = Util.coerceInputStream(inStream);
// read the magic number to confirm this file type
// (it better be ASCII, we're not doing utf-8 conversion)
var i;
for (i = 0; i < magic.length; i=i+1|0) {
if (magic.charCodeAt(i) !== inStream.readByte()) {
throw new Error("Bad magic");
}
}
// read the file size & create an appropriate output stream/buffer
var fileSize = Util.readUnsignedNumber(inStream) - 1;
var o = Util.coerceOutputStream(outStream, fileSize);
outStream = o.stream;
// call the guts to do the real decompression
guts(inStream, outStream, fileSize);
return o.retval;
};
};
// a helper for simple self-test of model encode
Util.compressWithModel = function (inStream, fileSize, model) {
var inSize = 0;
while (inSize !== fileSize) {
var ch = inStream.readByte();
if (ch === EOF) {
model.encode(256); // end of stream;
break;
}
model.encode(ch);
inSize++;
}
};
// a helper for simple self-test of model decode
Util.decompressWithModel = function (outStream, fileSize, model) {
var outSize = 0;
while (outSize !== fileSize) {
var ch = model.decode();
if (ch === 256) {
break; // end of stream;
}
outStream.writeByte(ch);
outSize++;
}
};
/** Write a number using a self-delimiting big-endian encoding. */
Util.writeUnsignedNumber = function (output, n) {
var bytes = [],
i;
do {
bytes.push(n & 0x7F);
// use division instead of shift to allow encoding numbers up to
// 2^53
n = Math.floor(n / 128);
} while (n !== 0);
bytes[0] |= 0x80; // mark end of encoding.
for (i = bytes.length - 1; i >= 0; i=i-1|0) {
output.writeByte(bytes[i]); // write in big-endian order
}
return output;
};
/** Read a number using a self-delimiting big-endian encoding. */
Util.readUnsignedNumber = function (input) {
var n = 0,
c;
while (true) {
c = input.readByte();
if (c & 0x80) {
n += c & 0x7F;
break;
}
// using + and * instead of << allows decoding numbers up to 2^53
n = (n + c) * 128;
}
return n;
};
// Compatibility thunks for Buffer/TypedArray varructors.
var zerofill = function zerofill(a) {
for (var i = 0, len = a.length; i < len; i=i+1|0) {
a[i] = 0;
}
return a;
};
var fallbackarray = function fallbackarray(size) {
return zerofill(new Array(size));
};
// Node 0.11.6 - 0.11.10ish don't properly zero fill typed arrays.
// See https://github.com/joyent/node/issues/6664
// Try to detect and workaround the bug.
var ensureZeroed = function id(a) {
return a;
};
if (typeof process !== 'undefined' && Array.prototype.some.call(new Uint32Array(128), function (x) {
return x !== 0;
})) {
//console.warn('Working around broken TypedArray');
ensureZeroed = zerofill;
}
/** Portable 8-bit unsigned buffer. */
Util.makeU8Buffer = typeof Uint8Array !== 'undefined' ? function (size) {
// Uint8Array ought to be automatically zero-filled
return ensureZeroed(new Uint8Array(size));
} : fallbackarray;
/** Portable 16-bit unsigned buffer. */
Util.makeU16Buffer = typeof Uint16Array !== 'undefined' ? function (size) {
// Uint16Array ought to be automatically zero-filled
return ensureZeroed(new Uint16Array(size));
} : fallbackarray;
/** Portable 32-bit unsigned buffer. */
Util.makeU32Buffer = typeof Uint32Array !== 'undefined' ? function (size) {
// Uint32Array ought to be automatically zero-filled
return ensureZeroed(new Uint32Array(size));
} : fallbackarray;
/** Portable 32-bit signed buffer. */
Util.makeS32Buffer = typeof Int32Array !== 'undefined' ? function (size) {
// Int32Array ought to be automatically zero-filled
return ensureZeroed(new Int32Array(size));
} : fallbackarray;
Util.arraycopy = function (dst, src) {
for (var i = 0, len = src.length; i < len; i=i+1|0) {
dst[i] = src[i];
}
return dst;
};
/** Highest bit set in a byte. */
var bytemsb = Uint8Array.of(0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 /* 256 */);
/** Find last set (most significant bit).
* @return the last bit set in the argument.
* <code>fls(0)==0</code> and <code>fls(1)==1</code>. */
var fls = Util.fls = function (v) {
if (v > 0xFFFFFFFF) {
// use floating-point mojo
return 32 + fls(Math.floor(v / 0x100000000));
}
if ((v & 0xFFFF0000) !== 0) {
if ((v & 0xFF000000) !== 0) {
return 24 + bytemsb[v >>> 24 & 0xFF];
} else {
return 16 + bytemsb[v >>> 16];
}
} else if ((v & 0x0000FF00) !== 0) {
return 8 + bytemsb[v >>> 8];
} else {
return bytemsb[v];
}
};
/** Returns ceil(log2(n)) */
Util.log2c = function (v) {
return v === 0 ? -1 : fls(v - 1);
};
return Util; // ensure varants are recognized as such.
}();
LogDistanceModel = function () {
/** Simple (log n)(n) distance model. */
// lengthBitsModelFactory will be called with arguments 2, 4, 8, 16, etc
// and must return an appropriate model or coder.
var LogDistanceModel = function LogDistanceModel(size, extraStates, lgDistanceModelFactory, lengthBitsModelFactory) {
var i;
var bits = Util.fls(size - 1);
this.extraStates = +extraStates || 0;
this.lgDistanceModel = lgDistanceModelFactory(1 + bits + extraStates);
// this.distanceModel[n] used for distances which are n-bits long,
// but only n-1 bits are encoded: the top bit is known to be one.
this.distanceModel = [];
for (i = 2; i <= bits; i=i+1|0) {
var numBits = i - 1;
this.distanceModel[i] = lengthBitsModelFactory(1 << numBits);
}
};
/* you can give this model arguments between 0 and (size-1), or else
a negative argument which is one of the 'extra states'. */
LogDistanceModel.prototype.encode = function (distance) {
if (distance < 2) {
// small distance or an 'extra state'
this.lgDistanceModel.encode(distance + this.extraStates);
return;
}
var lgDistance = Util.fls(distance);
this.lgDistanceModel.encode(lgDistance + this.extraStates);
// now encode the rest of the bits.
var rest = distance & (1 << lgDistance - 1) - 1;
this.distanceModel[lgDistance].encode(rest);
};
LogDistanceModel.prototype.decode = function () {
var lgDistance = this.lgDistanceModel.decode() - this.extraStates;
if (lgDistance < 2) {
return lgDistance; // this is a small distance or an 'extra state'
}
var rest = this.distanceModel[lgDistance].decode();
return (1 << lgDistance - 1) + rest;
};
return LogDistanceModel;
}();
Huffman = function () {
/* Adaptive Huffman code, using Vitter's algorithm ported from
* vitter.c at http://code.google.com/p/compression-code/downloads/list
* The original code was placed in the public domain, and so I
* also place this JavaScript port in the public domain.
* -- C. Scott Ananian <[email protected]>, 2013
* ps. some truly grotty C code in the originally, faithfully ported to
* evil comma-operator-using, assignment-in-if-condition JavaScript.
*/
// This code is adapted from Professor Vitter's
// article, Design and Analysis of Dynamic Huffman Codes,
// which appeared in JACM October 1987
// A design trade-off has been made to simplify the
// code: a node's block is determined dynamically,
// and the implicit tree structure is maintained,
// e.g. explicit node numbers are also implicit.
// Dynamic Huffman table weight ranking
// is maintained per Professor Vitter's
// invariant (*) for algorithm FGK:
// leaves precede internal nodes of the
// same weight in a non-decreasing ranking
// of weights using implicit node numbers:
// 1) leaves slide over internal nodes, internal nodes
// swap over groups of leaves, leaves are swapped
// into group leader position, but two internal
// nodes never change positions relative
// to one another.
// 2) weights are incremented by 2:
// leaves always have even weight values;
// internal nodes always have odd values.
// 3) even node numbers are always right children;
// odd numbers are left children in the tree.
// node 2 * HuffSize - 1 is always the tree root;
// node HuffEsc is the escape node;
// the tree is initialized by creating an
// escape node as the root.
// each new leaf symbol is paired with a new escape
// node into the previous escape node in the tree,
// until the last symbol which takes over the
// tree position of the escape node, and
// HuffEsc is left at zero.
// overall table size: 2 * HuffSize
// huff_init(alphabet_size, potential symbols used)
// huff_encode(next_symbol)
// next_symbol = huff_decode()
// huff_scale(by_bits) -- scale weights and re-balance tree
var HTable = function HTable(up, down, symbol, weight) {
this.up = up; // next node up the tree
this.down = down; // pair of down nodes
this.symbol = symbol; // node symbol value
this.weight = weight; // node weight
};
HTable.prototype.clone = function () {
return new HTable(this.up, this.down, this.symbol, this.weight);
};
HTable.prototype.set = function (htable) {
this.up = htable.up;
this.down = htable.down;
this.symbol = htable.symbol;
this.weight = htable.weight;
};
// initialize an adaptive coder
// for alphabet size, and count
// of nodes to be used
var Huffman = function Huffman(size, root, bitstream, max_weight) {
var i;
// default: all alphabet symbols are used
if (!root || root > size) root = size;
// create the initial escape node
// at the tree root
if (root <<= 1) {
root--;
}
// create root+1 htables (coding table)
// XXX this could be views on a backing Uint32 array?
this.table = [];
for (i = 0; i <= root; i=i+1|0) {
this.table[i] = new HTable(0, 0, 0, 0);
}
// this.map => mapping for symbols to nodes
this.map = [];
// this.size => the alphabet size
if (this.size = size) {
for (i = 0; i < size; i=i+1|0) {
this.map[i] = 0;
}
}
// this.esc => the current tree height
// this.root => the root of the tree
this.esc = this.root = root;
if (bitstream) {
this.readBit = bitstream.readBit.bind(bitstream);
this.writeBit = bitstream.writeBit.bind(bitstream);
}
this.max_weight = max_weight; // may be null or undefined
};
// factory interface
Huffman.factory = function (bitstream, max_weight) {
return function (size) {
return new Huffman(size, size, bitstream, max_weight);
};
};
// split escape node to incorporate new symbol
Huffman.prototype.split = function (symbol) {
var pair, node;
// is the tree already full???
if (pair = this.esc) {
this.esc--;
} else {
return 0;
}
// if this is the last symbol, it moves into
// the escape node's old position, and
// this.esc is set to zero.
// otherwise, the escape node is promoted to
// parent a new escape node and the new symbol.
if (node = this.esc) {
this.table[pair].down = node;
this.table[pair].weight = 1;
this.table[node].up = pair;
this.esc--;
} else {
pair = 0;
node = 1;
}
// initialize the new symbol node
this.table[node].symbol = symbol;
this.table[node].weight = 0;
this.table[node].down = 0;
this.map[symbol] = node;
// initialize a new escape node.
this.table[this.esc].weight = 0;
this.table[this.esc].down = 0;
this.table[this.esc].up = pair;
return node;
};
// swap leaf to group leader position
// return symbol's new node
Huffman.prototype.leader = function (node) {
var weight = this.table[node].weight;
var leader = node,
prev,
symbol;
while (weight === this.table[leader + 1].weight) {
leader++;
}
if (leader === node) {
return node;
}
// swap the leaf nodes
symbol = this.table[node].symbol;
prev = this.table[leader].symbol;
this.table[leader].symbol = symbol;
this.table[node].symbol = prev;
this.map[symbol] = leader;
this.map[prev] = node;
return leader;
};
// slide internal node up over all leaves of equal weight;
// or exchange leaf with next smaller weight internal node
// return node's new position
Huffman.prototype.slide = function (node) {
var next = node;
var swap;
swap = this.table[next++].clone();
// if we're sliding an internal node, find the
// highest possible leaf to exchange with
if (swap.weight & 1) {
while (swap.weight > this.table[next + 1].weight) {
next++;
}
}
// swap the two nodes
this.table[node].set(this.table[next]);
this.table[next].set(swap);
this.table[next].up = this.table[node].up;
this.table[node].up = swap.up;
// repair the symbol map and tree structure
if (swap.weight & 1) {
this.table[swap.down].up = next;
this.table[swap.down - 1].up = next;
this.map[this.table[node].symbol] = node;
} else {
this.table[this.table[node].down - 1].up = node;
this.table[this.table[node].down].up = node;
this.map[swap.symbol] = next;