-
Notifications
You must be signed in to change notification settings - Fork 0
/
lzp3.js
1926 lines (1685 loc) · 63.5 KB
/
lzp3.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
var EOF = -1;
var Stream = function() {
/* 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;
};
// reasonable default implementation of 'eof'
Stream.prototype.eof = function() { return !!this._eof; };
// not all readable streams are seekable
Stream.prototype.seek = function(pos) {
throw new Error('Stream is not seekable.');
};
Stream.prototype.tell = function() {
throw new Error('Stream is not seekable.');
};
// you must define one of write / writeByte for a writable stream
Stream.prototype.writeByte = function(_byte) {
var buf = [ _byte ];
this.write(buf, 0, 1);
};
Stream.prototype.write = function(buf, bufOffset, length) {
var i;
for (i=0; i<length; i++) {
this.writeByte(buf[bufOffset + i]);
}
return length;
};
// flush will happily do nothing if you don't override it.
Stream.prototype.flush = function() { };
// export EOF as a constant.
Stream.EOF = EOF;
var BitStream = function(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;
};
// seekable iff the provided stream is
this.seekBit = function(pos) {
var n_byte = pos >>> 3;
var n_bit = pos - (n_byte*8);
this.seek(n_byte);
this._eof = false;
this.readBits(n_bit);
};
this.tellBit = function() {
var pos = stream.tell() * 8;
var b = bufferByte;
while ((b & 0xFF) !== 0) {
pos--;
b <<= 1;
}
return pos;
};
// 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++) {
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--) {
this.writeBit( (value >>> i) & 1 );
}
};
var Context1Model = function(modelFactory, contextSize, alphabetSize) {
var i;
this.literalModel = [];
// even if there's an EOF symbol, we don't need a context for it!
for (i=0; i<contextSize; i++) {
this.literalModel[i] = modelFactory(alphabetSize);
}
};
Context1Model.prototype.encode = function(ch, context) {
this.literalModel[context].encode(ch);
};
Context1Model.prototype.decode = function(context) {
return this.literalModel[context].decode();
};
/** Simple self-test. */
Context1Model.MAGIC='ctx1';
Context1Model.compressFile = Util.compressFileHelper(Context1Model.MAGIC, function(inStream, outStream, fileSize, props) {
var bitstream = new BitStream(outStream);
var alphabetSize = 256;
if (fileSize < 0) { alphabetSize++; }
var coder = Huffman.factory(bitstream, 8191);
var model = new Context1Model(coder, 256, alphabetSize);
var lastchar = 0x20;
var modelp = {
encode: function(symbol) {
model.encode(symbol, lastchar);
lastchar = symbol;
}
};
Util.compressWithModel(inStream, fileSize, modelp);
bitstream.flush();
});
Context1Model.decompressFile = Util.decompressFileHelper(Context1Model.MAGIC, function(inStream, outStream, fileSize) {
var bitstream = new BitStream(inStream);
var alphabetSize = 256;
if (fileSize < 0) { alphabetSize++; }
var coder = Huffman.factory(bitstream, 8191);
var model = new Context1Model(coder, 256, alphabetSize);
var lastchar = 0x20;
var modelp = {
decode: function() {
var symbol = model.decode(lastchar);
lastchar = symbol;
return symbol;
}
};
Util.decompressWithModel(outStream, fileSize, modelp);
});
var LOG_PROB_TOTAL = 8;
var PROB_TOTAL = 1 << LOG_PROB_TOTAL;
var MAX_ESCAPE_COUNT = 40;
var DefSumModel = function(coder, size, isDecoder) {
var i;
console.assert(size < 300); // not meant for sparse
var ESCAPE = this.numSyms = size;
this.coder = coder;
this.prob = Util.makeU16Buffer(size+2); /* size + ESC + 1 */
this.escape = Util.makeU16Buffer(size+1); /* size + 1*/
this.update = Util.makeU16Buffer(size+1); /* size + ESC */
this.prob[ESCAPE+1] = PROB_TOTAL;
for (i=0; i<=this.numSyms; i++) {
this.escape[i] = i;
}
this.updateCount = 0;
this.updateThresh = PROB_TOTAL - Math.floor(PROB_TOTAL / 2);
if (!isDecoder) { return; }
// extra tables for fast decoding
this.probToSym = Util.makeU16Buffer(PROB_TOTAL);
this.escProbToSym = Util.makeU16Buffer(this.numSyms);
for (i=0; i<PROB_TOTAL; i++) {
this.probToSym[i] = ESCAPE;
}
for (i=0; i<this.numSyms; i++) {
this.escProbToSym[i] = i;
}
};
DefSumModel.factory = function(coder, isDecoder) {
return function(size) { return new DefSumModel(coder, size, isDecoder); };
};
DefSumModel.prototype._update = function(symbol, isDecoder) {
if (symbol === this.numSyms) {
// some special cases for the escape character
if (this.update[symbol] >= MAX_ESCAPE_COUNT) { return; } // hard limit
// don't let an escape character trigger an update, because then the
// escaped character might find itself unescaped after the tables have
// been updated!
if (this.updateCount >= (this.updateThresh - 1)) { return; }
}
this.update[symbol]++;
this.updateCount++;
// is it time to transfer the updated probabilities?
if (this.updateCount < this.updateThresh) {
return; //defer update
}
var cumProb, cumEscProb, odd, i, j, k;
this.escape[0] = this.prob[0] = cumProb = cumEscProb = odd = 0;
for (i=0; i < this.numSyms+1; i++) {
var newProb = ((this.prob[i+1]-this.prob[i]) >>> 1) + this.update[i];
if (newProb) {
// live 'un
this.prob[i] = cumProb;
cumProb += newProb;
if (newProb & 1) { odd++; }
this.escape[i] = cumEscProb;
} else {
// this symbol will escape
this.prob[i] = cumProb;
this.escape[i] = cumEscProb;
cumEscProb++;
}
}
this.prob[i] = cumProb;
console.assert(cumProb === PROB_TOTAL);
/* how many updates will be required after current probs are halved? */
this.updateThresh = PROB_TOTAL - Math.floor((cumProb-odd) / 2);
/* reset the update table */
for (i=0; i < (this.numSyms + 1); i++) {
this.update[i] = 0;
}
this.update[this.numSyms] = 1; // ensure that escape never goes away
this.updateCount = 1;
/* compute decode table, if this is a decoder */
if (!isDecoder) { return; }
for (i=0, j=0, k=0; i<(this.numSyms+1); i++) {
var probLimit = this.prob[i+1];
for (; j<probLimit; j++) {
this.probToSym[j] = i;
}
var escProbLimit = this.escape[i+1];
for (; k<escProbLimit; k++) {
this.escProbToSym[k] = i;
}
}
};
DefSumModel.prototype.encode = function(symbol) {
var lt_f = this.prob[symbol];
var sy_f = this.prob[symbol+1] - lt_f;
console.assert(this.prob[this.numSyms+1] === PROB_TOTAL);
if (sy_f) {
this.coder.encodeShift(sy_f, lt_f, LOG_PROB_TOTAL);
return this._update(symbol);
}
// escape!
console.assert(symbol !== this.numSyms); // catch infinite recursion
this.encode(this.numSyms); // guaranteed non-zero probability
// code symbol as literal, taking advantage of reduced escape range.
lt_f = this.escape[symbol];
sy_f = this.escape[symbol+1] - lt_f;
var tot_f = this.escape[this.numSyms];
this.coder.encodeFreq(sy_f, lt_f, tot_f);
return this._update(symbol);
};
DefSumModel.prototype.decode = function() {
var prob = this.coder.decodeCulShift(LOG_PROB_TOTAL);
var symbol = this.probToSym[prob];
var lt_f = this.prob[symbol];
var sy_f = this.prob[symbol+1] - lt_f;
this.coder.decodeUpdate(sy_f, lt_f, PROB_TOTAL);
this._update(symbol, true);
if (symbol !== this.numSyms) {
return symbol;
}
// escape!
var tot_f = this.escape[this.numSyms];
prob = this.coder.decodeCulFreq(tot_f);
symbol = this.escProbToSym[prob];
lt_f = this.escape[symbol];
sy_f = this.escape[symbol+1] - lt_f;
this.coder.decodeUpdate(sy_f, lt_f, tot_f);
this._update(symbol, true);
return symbol;
};
DefSumModel.MAGIC='dfsm';
/** Simple order-0 compressor, as self-test. */
DefSumModel.compressFile = Util.compressFileHelper(DefSumModel.MAGIC, function(inStream, outStream, fileSize, props, finalByte) {
var range = new RangeCoder(outStream);
range.encodeStart(finalByte, 1);
var model = new DefSumModel(range, (fileSize<0) ? 257 : 256);
Util.compressWithModel(inStream, fileSize, model);
range.encodeFinish();
},true);
/** Simple order-0 decompresser, as self-test. */
DefSumModel.decompressFile = Util.decompressFileHelper(DefSumModel.MAGIC, function(inStream, outStream, fileSize) {
var range = new RangeCoder(inStream);
range.decodeStart(true/*already read the final byte*/);
var model = new DefSumModel(range, (fileSize<0) ? 257 : 256, true);
Util.decompressWithModel(outStream, fileSize, model);
range.decodeFinish();
});
/** We store two probabilities in a U32, so max prob is going to be 0xFFFF */
var DEFAULT_MAX_PROB = 0xFF00;
var DEFAULT_INCREMENT= 0x0100;
var ESC_MASK = 0x0000FFFF, ESC_SHIFT = 0;
var SYM_MASK = 0xFFFF0000, SYM_SHIFT = 16;
var SCALE_MASK=0xFFFEFFFE;
var FenwickModel = function(coder, size, max_prob, increment) {
this.coder = coder;
this.numSyms = size + 1; // save space for an escape symbol
this.tree = Util.makeU32Buffer(this.numSyms*2);
this.increment = (+increment) || DEFAULT_INCREMENT;
this.max_prob = (+max_prob) || DEFAULT_MAX_PROB;
// sanity-check to prevent overflow.
console.assert((this.max_prob + (this.increment-1)) <= 0xFFFF);
console.assert(size <= 0xFFFF);
// record escape probability as 1.
var i;
for (i=0; i<size; i++) {
this.tree[this.numSyms + i] = // escape prob=1, sym prob = 0
(1 << ESC_SHIFT) | (0 << SYM_SHIFT);
}
this.tree[this.numSyms + i] = // escape prob = 0, sym prob = 1
(0 << ESC_SHIFT) | (this.increment << SYM_SHIFT);
this._sumTree();
// probability sums are in this.tree[1]. this.tree[0] is unused.
};
FenwickModel.factory = function(coder, max_prob, increment) {
return function(size) {
return new FenwickModel(coder, size, max_prob, increment);
};
};
FenwickModel.prototype.clone = function() {
var newModel = new FenwickModel(this.coder, this.size,
this.max_prob, this.increment);
var i;
for (i=1; i<this.tree.length; i++) {
newModel.tree[i] = this.tree[i];
}
return newModel;
};
FenwickModel.prototype.encode = function(symbol) {
var i = this.numSyms + symbol;
var sy_f = this.tree[i];
var mask = SYM_MASK, shift = SYM_SHIFT;
var update = (this.increment << SYM_SHIFT);
if ((sy_f & SYM_MASK) === 0) { // escape!
this.encode(this.numSyms-1);
mask = ESC_MASK;
update -= (1<<ESC_SHIFT); // not going to escape no mo'
shift = ESC_SHIFT;
} else if (symbol === (this.numSyms-1) &&
((this.tree[1] & ESC_MASK) >>> ESC_SHIFT) === 1) {
// this is the last escape, zero it out
update = -this.tree[i];
}
// sum up the proper lt_f
var lt_f = 0;
while (i > 1) {
var isRight = (i & 1);
var parent = (i >>> 1);
// if we're the right child, we need to
// add the prob from the left child
if (isRight) {
lt_f += this.tree[2*parent];
}
// update sums
this.tree[i] += update; // increase sym / decrease esc
i = parent;
}
var tot_f = this.tree[1];
this.tree[1] += update; // update prob in root
sy_f = (sy_f & mask) >>> shift;
lt_f = (lt_f & mask) >>> shift;
tot_f =(tot_f& mask) >>> shift;
this.coder.encodeFreq(sy_f, lt_f, tot_f);
// rescale?
if ((( this.tree[1] & SYM_MASK ) >>> SYM_SHIFT) >= this.max_prob) {
this._rescale();
}
};
FenwickModel.prototype._decode = function(isEscape) {
var mask = SYM_MASK, shift = SYM_SHIFT;
var update = (this.increment << SYM_SHIFT);
if (isEscape) {
mask = ESC_MASK;
update -= (1 << ESC_SHIFT);
shift = ESC_SHIFT;
}
var tot_f = (this.tree[1] & mask) >>> shift;
var prob = this.coder.decodeCulFreq(tot_f);
// travel down the tree looking for this
var i = 1, lt_f = 0;
while (i < this.numSyms) {
this.tree[i] += update;
// look at probability in left child.
var leftProb = (this.tree[2*i] & mask) >>> shift;
i *= 2;
if ((prob-lt_f) >= leftProb) {
lt_f += leftProb;
i++; // take the right child.
}
}
var symbol = i - this.numSyms;
var sy_f = (this.tree[i] & mask) >>> shift;
this.tree[i] += update;
this.coder.decodeUpdate(sy_f, lt_f, tot_f);
// was this the last escape?
if (symbol === (this.numSyms-1) &&
((this.tree[1] & ESC_MASK) >>> ESC_SHIFT) === 1) {
update = -this.tree[i]; // zero it out
while (i >= 1) {
this.tree[i] += update;
i = (i >>> 1); // parent
}
}
// rescale?
if ((( this.tree[1] & SYM_MASK ) >>> SYM_SHIFT) >= this.max_prob) {
this._rescale();
}
return symbol;
};
FenwickModel.prototype.decode = function() {
var symbol = this._decode(false); // not escape
if (symbol === (this.numSyms-1)) {
// this was an escape!
symbol = this._decode(true); // an escape!
}
return symbol;
};
FenwickModel.prototype._rescale = function() {
var i, prob, noEscape = true;
// scale symbols (possible causing them to escape)
for (i=0; i < this.numSyms-1; i++) {
prob = this.tree[this.numSyms + i];
if ((prob & ESC_MASK) !== 0) {
// this symbol escapes
noEscape = false;
continue;
}
prob = (prob & SCALE_MASK) >>> 1;
if (prob === 0) {
// this symbol newly escapes
prob = (1 << ESC_SHIFT);
noEscape = false;
}
this.tree[this.numSyms + i] = prob;
}
// scale the escape symbol
prob = this.tree[this.numSyms + i];
prob = (prob & SCALE_MASK) >>> 1;
// prob should be zero if there are no escaping symbols, otherwise
// it must be at least 1.
if (noEscape) { prob = 0; }
else if (prob === 0) { prob = (1 << SYM_SHIFT); }
this.tree[this.numSyms + i] = prob;
// sum it all up afresh
this._sumTree();
};
FenwickModel.prototype._sumTree = function() {
var i;
// sum it all. (we know we won't overflow)
for (i=this.numSyms - 1; i > 0; i--) {
this.tree[i] = this.tree[2*i] + this.tree[2*i + 1];
}
};
FenwickModel.MAGIC = 'fenw';
/** Simple order-0 compressor, as self-test. */
FenwickModel.compressFile = Util.compressFileHelper(FenwickModel.MAGIC, function(inStream, outStream, fileSize, props, finalByte) {
var range = new RangeCoder(outStream);
range.encodeStart(finalByte, 1);
var model = new FenwickModel(range, (fileSize<0) ? 257 : 256);
Util.compressWithModel(inStream, fileSize, model);
range.encodeFinish();
}, true);
/** Simple order-0 decompresser, as self-test. */
FenwickModel.decompressFile = Util.decompressFileHelper(FenwickModel.MAGIC, function(inStream, outStream, fileSize) {
var range = new RangeCoder(inStream);
range.decodeStart(true/*already read the final byte*/);
var model = new FenwickModel(range, (fileSize<0) ? 257 : 256);
Util.decompressWithModel(outStream, fileSize, model);
range.decodeFinish();
});
var HTable = function(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(size, root, bitstream, max_weight) {
var i;
// default: all alphabet symbols are used
console.assert(size && typeof(size)==='number');
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++) {
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++) {
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 {
console.assert(false);
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;
}
return next;
};
// increment symbol weight and re balance the tree.
Huffman.prototype.increment = function(node) {
var up;
// obviate swapping a parent with its child:
// increment the leaf and proceed
// directly to its parent.
// otherwise, promote leaf to group leader position in the tree
if( this.table[node].up === node + 1 ) {
this.table[node].weight += 2;
node++;
} else {
node = this.leader (node);
}
// increase the weight of each node and slide
// over any smaller weights ahead of it
// until reaching the root
// internal nodes work upwards from
// their initial positions; while
// symbol nodes slide over first,
// then work up from their final
// positions.
while( this.table[node].weight += 2, up = this.table[node].up ) {
while( this.table[node].weight > this.table[node + 1].weight ) {
node = this.slide (node);
}
if( this.table[node].weight & 1 ) {
node = up;
} else {
node = this.table[node].up;
}
}
/* Re-scale if necessary. */
if (this.max_weight) {
if (this.table[this.root].weight >= this.max_weight) {
this.scale(1);
}
}
};
// scale all weights and re-balance the tree
// zero weight nodes are removed from the tree
// by sliding them out the left of the rank list
Huffman.prototype.scale = function(bits) {
var node = this.esc, weight, prev;
// work up the tree from the escape node
// scaling weights by the value of bits
while( ++node <= this.root ) {
// recompute the weight of internal nodes;
// slide down and out any unused ones
if( this.table[node].weight & 1 ) {
if( weight = this.table[this.table[node].down].weight & ~1 ) {
weight += this.table[this.table[node].down - 1].weight | 1;
}
// remove zero weight leaves by incrementing HuffEsc
// and removing them from the symbol map. take care
} else if( !(weight = this.table[node].weight >> bits & ~1) ) {
if( this.map[this.table[node].symbol] = 0, this.esc++ ) {
this.esc++;
}
}
// slide the scaled node back down over any
// previous nodes with larger weights
this.table[node].weight = weight;
prev = node;
while( weight < this.table[--prev].weight ) {
this.slide(prev);
}
}
// prepare a new escape node
this.table[this.esc].down = 0;
};
// send the bits for an escaped symbol
Huffman.prototype.sendid = function(symbol) {
var empty = 0, max;
// count the number of empty symbols
// before the symbol in the table
while( symbol-- ) {
if( !this.map[symbol] ) {
empty++;
}
}
// send LSB of this count first, using
// as many bits as are required for
// the maximum possible count
if( max = this.size - Math.floor((this.root - this.esc) / 2) - 1 ) {
do {
this.writeBit(empty & 1);
empty >>= 1;
} while( max >>= 1 );
}
};
// encode the next symbol
Huffman.prototype.encode = function(symbol) {
var emit = 1, bit;
var up, idx, node;
if( symbol < this.size ) {
node = this.map[symbol];
} else {
console.assert(false);
return;
}
// for a new symbol, direct the receiver to the escape node
// but refuse input if table is already full.
if( !(idx = node) ) {
if( !(idx = this.esc) ) {
return;
}
}
// accumulate the code bits by
// working up the tree from
// the node to the root
while( up = this.table[idx].up ) {
emit <<= 1; emit |= idx & 1; idx = up;
}
// send the code, root selector bit first
while( bit = emit & 1, emit >>= 1 ) {
this.writeBit(bit);
}
// send identification and incorporate
// new symbols into the tree
if( !node ) {
this.sendid(symbol);
node = this.split(symbol);
}
// adjust and re-balance the tree
this.increment(node);
};
// read the identification bits
// for an escaped symbol
Huffman.prototype.readid = function() {
var empty = 0, bit = 1, max, symbol;
// receive the symbol, LSB first, reading
// only the number of bits necessary to
// transmit the maximum possible symbol value
if( max = this.size - Math.floor((this.root - this.esc) / 2) - 1 ) {
do {
empty |= this.readBit() ? bit : 0;
bit <<= 1;
} while( max >>= 1 );
}
// the count is of unmapped symbols
// in the table before the new one
for( symbol = 0; symbol < this.size; symbol++ ) {
if( !this.map[symbol] ) {
if( !empty-- ) {
return symbol;
}
}
}
// oops! our count is too big, either due
// to a bit error, or a short node count
// given to huff_init.
console.assert(false);
return 0;
};
// decode the next symbol
Huffman.prototype.decode = function() {
var node = this.root;
var symbol, down;
// work down the tree from the root
// until reaching either a leaf
// or the escape node. A one
// bit means go left, a zero
// means go right.
while( down = this.table[node].down ) {
if( this.readBit() ) {
node = down - 1; // the left child precedes the right child
} else {
node = down;
}
}
// sent to the escape node???
// refuse to add to a full tree
if( node === this.esc ) {
if( this.esc ) {
symbol = this.readid ();
node = this.split (symbol);
} else {
console.assert(false);
return 0;
}
} else {
symbol = this.table[node].symbol;
}
// increment weights and re-balance
// the coding tree
this.increment (node);
return symbol;
};
// stand alone compressor, mostly for testing
Huffman.MAGIC = 'huff';
Huffman.compressFile = Util.compressFileHelper(Huffman.MAGIC, function(input, output, size, props) {
var bitstream = new BitStream(output);