forked from powzix/ooz
-
Notifications
You must be signed in to change notification settings - Fork 12
/
compr_entropy.cpp
1347 lines (1161 loc) · 38.9 KB
/
compr_entropy.cpp
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
// This file is not GPL. It may be used for educational purposes only.
#include "stdafx.h"
#include "compr_entropy.h"
#include "compr_util.h"
#include <algorithm>
#include <vector>
#include "qsort.h"
#pragma warning (disable: 4018)
float CombineCostComponents(int platforms, float a, float b, float c, float d) {
if ((platforms & 0xf) == 0)
return (a + b + c + d) * 0.25f;
int n = 0;
float sum = 0;
if (platforms & 1) sum += c * 0.762f, n++;
if (platforms & 2) sum += a * 1.130f, n++;
if (platforms & 4) sum += d * 1.310f, n++;
if (platforms & 8) sum += b * 0.961f, n++;
return sum / n;
}
float CombineCostComponents1(int platforms, float v, float a, float b, float c, float d) {
return CombineCostComponents(platforms, v * a, v * b, v * c, v * d);
}
float CombineCostComponents1A(int platforms, float v, float a, float b, float c, float d,
float x, float y, float z, float w) {
return CombineCostComponents(platforms, v * a + x, v * b + y, v * c + z, v * d + w);
}
float GetTime_SingleHuffman(int platforms, int count, int numsyms) {
return CombineCostComponents(
platforms,
1880.931f + count * 3.243f + numsyms * 10.960f,
2219.6531f + count * 2.993f + numsyms * 24.622f,
2889.8579f + count * 2.468f + numsyms * 21.296f,
2029.866f + count * 2.699f + numsyms * 8.459f);
}
float GetTime_DoubleHuffman(int platforms, int count, int numsyms) {
return CombineCostComponents(
platforms,
2029.917f + count * 2.436f + numsyms * 10.792f,
2540.026f + count * 2.087f + numsyms * 20.994f,
3227.433f + count * 2.501f + numsyms * 18.925f,
2084.978f + count * 1.875f + numsyms * 8.9510f);
}
float GetTime_AdvRLE(int platforms, int src_size) {
return CombineCostComponents1A(platforms, src_size,
0.172f, 0.282f, 0.377f, 0.161f,
284.970f, 326.121f, 388.669f, 274.267f);
}
float GetTime_Memset(int platforms, int src_size) {
return CombineCostComponents1A(platforms, src_size,
0.125f, 0.171f, 0.256f, 0.083f,
28.0f, 53.0f, 58.0f, 29.0f);
}
void CountBytesHistoU8(const uint8 *data, size_t data_size, HistoU8 *histo) {
// todo: optimize
memset(histo, 0, sizeof(HistoU8));
for (size_t i = 0; i < data_size; i++)
histo->count[data[i]]++;
}
uint GetHistoSum(const uint *a, size_t n) {
// todo: optimize
uint sum = 0;
for (size_t i = 0; i < n; i++)
sum += a[i];
return sum;
}
uint GetHistoSum(const HistoU8 &h) {
// todo: optimize
uint sum = 0;
for (size_t i = 0; i < 256; i++)
sum += h.count[i];
return sum;
}
uint GetHistoMax(const HistoU8 &histo) {
// todo: optimize
uint m = 0;
for (size_t i = 0; i < 256; i++)
m = std::max(m, histo.count[i]);
return m;
}
void ConvertHistoToCost(const HistoU8 &src, uint *dst, int extra, int q) {
int total_count = 256 + 4 * GetHistoSum(src);
int bits = 32 - BSR(total_count);
int base = (bits << 13) - GetLog2Interpolate(total_count << bits);
int sum_of_bits = 0;
for (size_t i = 0; i < 256; i++) {
int count = src.count[i] * 4 + 1;
bits = 32 - BSR(count);
int bp = (32 * ((bits << 13) - GetLog2Interpolate(count << bits) - base)) >> 13;
sum_of_bits += count * bp;
dst[i] = bp + extra;
}
if (sum_of_bits > q * total_count) {
for (size_t i = 0; i < 256; i++)
dst[i] = 8 * 32 + extra;
}
}
uint GetHistoCostApprox(const uint *histo, size_t arrsize, int histo_sum) {
if (histo_sum <= 1)
return 40;
int factor = 0x40000000u / histo_sum;
uint zeros_run = 0, nonzero_entries = 0;
uint32 bit_usagez = 0, bit_usage = 0;
uint64 bit_usagef = 0;
for (size_t i = 0; i != arrsize; i++) {
uint32 v = histo[i];
if (!v) {
zeros_run++;
continue;
}
nonzero_entries++;
if (zeros_run) {
bit_usagez += 2 * BSR(zeros_run + 1) + 1;
zeros_run = 0;
} else {
bit_usagez += 1;
}
bit_usage += BSR(v) * 2 + 1;
bit_usagef += v * (uint64)kLog2LookupTable[factor * v >> 17];
}
if (nonzero_entries == 1)
return 6 * 8;
bit_usagez += 2 * BSR(zeros_run + 1) + 1;
bit_usagez = std::min<uint>(bit_usagez, 8 * nonzero_entries);
return (int)(bit_usagef >> 13) + bit_usage + bit_usagez + 5 * 8;
}
uint GetHistoCostApprox(const HistoU8 &h, int histo_sum) {
return GetHistoCostApprox(h.count, 256, histo_sum);
}
float GetCost_SingleHuffman(const HistoU8 &histo, int histo_sum, float speed_tradeoff, int platforms) {
double a = GetTime_SingleHuffman(platforms, histo_sum, 128);
uint b = GetHistoCostApprox(histo, histo_sum);
return a * speed_tradeoff + b * 0.125f;
}
#include "log_lookup.h"
static const uint16 kSomeLookup[65] = {
0, 183, 364, 541, 716, 889, 1059, 1227, 1392, 1555, 1716, 1874,
2031, 2186, 2338, 2489, 2637, 2784, 2929, 3072, 3214, 3354, 3492,
3629, 3764, 3897, 4029, 4160, 4289, 4417, 4543, 4668, 4792, 4914,
5036, 5156, 5274, 5392, 5509, 5624, 5738, 5851, 5963, 6074, 6184,
6293, 6401, 6508, 6614, 6719, 6823, 6926, 7029, 7130, 7231, 7330,
7429, 7527, 7625, 7721, 7817, 7912, 8006, 8099, 8192,
};
int GetLog2Interpolate(uint x) {
return kSomeLookup[x >> 26] + ((((x >> 10) & 0xFFFF) * (kSomeLookup[(x >> 26) + 1] - kSomeLookup[x >> 26]) + 0x8000) >> 16);
}
int EncodeArrayU8_Memcpy(uint8 *dst, uint8 *dst_end, const uint8 *src, int size) {
if (size > 0x3FFFF)
return -1;
if (dst_end - dst < size + 3)
return -1;
dst[0] = (uint8)(size >> 16);
dst[1] = (uint8)(size >> 8);
dst[2] = (uint8)(size >> 0);
memcpy(dst + 3, src, size);
return size + 3;
}
int EncodeArrayU8(uint8 *dst, uint8 *dst_end, const uint8 *src, int src_size, int encode_opts, float speed_tradeoff, int platforms, float *cost_ptr, int level, HistoU8 *histo_ptr) {
HistoU8 histo;
if (src_size > 32) {
CountBytesHistoU8(src, src_size, &histo);
if (histo_ptr)
*histo_ptr = histo;
return EncodeArrayU8WithHisto(dst, dst_end, src, src_size, histo, encode_opts, speed_tradeoff, platforms, cost_ptr, level);
} else {
*cost_ptr = src_size + 3;
return EncodeArrayU8_Memcpy(dst, dst_end, src, src_size);
}
}
int MakeCompactChunkHdr(uint8 *src, int size, float *cost) {
int size_org = size;
if (size > 4095 + 5)
return size;
Kraken_GetBlockSize(src, &src[size], &size, 0x20000);
uint chunk_type = *src >> 4;
if (chunk_type == 0) {
if (size > 4095)
return size_org;
src[0] = 0x80 | (size >> 8);
src[1] = (uint8)size;
memmove(src + 2, src + 3, size);
*cost -= 1;
return size + 2;
} else {
int csize = size_org - 5;
if (csize > 1023)
return size_org;
int dsize = size - csize - 1;
if (dsize > 1023)
return size_org;
*(uint32*)src = _byteswap_ulong((((chunk_type | 0x8) << 20) + (dsize << 10) + csize) << 8);
memmove(src + 3, src + 5, csize);
*cost -= 2;
return csize + 3;
}
}
int EncodeArrayU8CompactHeader(uint8 *dst, uint8 *dst_end, const uint8 *src, int src_size, int opts, float speed_tradeoff, int platforms, float *cost_ptr, int level, HistoU8 *histo) {
int n = EncodeArrayU8(dst, dst_end, src, src_size, opts, speed_tradeoff, platforms, cost_ptr, level, histo);
return n >= 0 ? MakeCompactChunkHdr(dst, n, cost_ptr) : -1;
}
uint8 *WriteChunkHeader(uint8 *dst, int mode, int dsize, int csize) {
dst[0] = (mode << 4) + ((dsize - 1) >> 14);
*(uint32*)(dst + 1) = _byteswap_ulong(((dsize - 1) << 18) + csize);
return dst + 5 + csize;
}
int EncodeArrayU8_MaybeConcat(uint8 *dst, uint8 *dst_end, const uint8 *src, int src_size, int opts, float speed_tradeoff, int platforms, float *cost_ptr, int level, HistoU8 *histo, int part_size) {
if (!part_size || part_size == src_size || src_size <= 32)
return EncodeArrayU8(dst, dst_end, src, src_size, opts, speed_tradeoff, platforms, cost_ptr, level, histo);
float cost1 = kInvalidCost;
float cost2 = kInvalidCost;
int n1 = EncodeArrayU8CompactHeader(dst + 6, dst_end, src, part_size,
opts & ~kEntropyOpt_MultiArray,
speed_tradeoff, platforms, &cost1, level, 0);
int n2 = EncodeArrayU8CompactHeader(dst + n1 + 6, dst_end, src + part_size, src_size - part_size,
opts & ~kEntropyOpt_MultiArray,
speed_tradeoff, platforms, &cost2, level, 0);
int total_bytes = 6 + n1 + n2;
float total_cost = 6.0f + cost1 + cost2;
WriteChunkHeader(dst, 5, src_size, total_bytes - 5);
dst[5] = 2;
*cost_ptr = total_cost;
int n = EncodeArrayU8(dst, dst_end, src, src_size, opts, speed_tradeoff, platforms, cost_ptr, level, histo);
if (n <= 0) {
if (histo)
CountBytesHistoU8(src, src_size, histo);
return total_bytes;
}
return n;
}
int EncodeArrayU8_Memset(uint8 *dst, uint8 *dst_end, const uint8 *src, int src_size, int opts, float speed_tradeoff, int platforms, float *cost_ptr) {
if (src_size < 6) {
*cost_ptr = src_size + 3;
return EncodeArrayU8_Memcpy(dst, dst_end, src, src_size);
}
int dst_size = dst_end - dst;
if (opts & kEntropyOpt_SupportsShortMemset) {
if (dst_size < 6)
return -1;
float cost = GetTime_Memset(platforms, src_size) * speed_tradeoff + 6;
if (cost < *cost_ptr) {
*cost_ptr = cost;
dst[5] = *src;
return WriteChunkHeader(dst, 3, src_size, 1) - dst;
}
} else {
if (dst_size < 8)
return -1;
float cost = GetTime_Memset(platforms, src_size) * speed_tradeoff + 8;
if (cost < *cost_ptr) {
*cost_ptr = cost;
uint8 v = *src;
dst[5] = 0;
dst[6] = 0x40 | (v >> 2);
dst[7] = v << 6;
return WriteChunkHeader(dst, 2, src_size, 3) - dst;
}
}
return -1;
}
static const uint8 *ScanForNextRLE3(const uint8 *src, const uint8 *src_end) {
while (src < src_end) {
__m128i v0 = _mm_loadu_si128((__m128i*)src);
__m128i v1 = _mm_loadu_si128((__m128i*)(src + 1));
__m128i v2 = _mm_loadu_si128((__m128i*)(src + 2));
int eq_mask = _mm_movemask_epi8(_mm_and_si128(_mm_cmpeq_epi8(v0, v1), _mm_cmpeq_epi8(v0, v2)));
if (eq_mask != 0)
return src + BSF(eq_mask);
src += 16;
}
return src;
}
static const uint8 *GetRLELength(const uint8 *src, const uint8 *src_end, const uint8 *safe_end) {
uint64 v0 = *(uint64*)src;
uint64 v1 = *(uint64*)(src + 1);
__m128i p;
if (v0 != v1)
return src + (BSF64(v0 ^ v1) >> 3) + 1;
if (src_end - src >= 25)
src += 8;
p = _mm_loadu_si128((__m128i*)src);
src += 1;
while (src < safe_end) {
int mask = _mm_movemask_epi8(_mm_cmpeq_epi8(_mm_loadu_si128((__m128i *)src), p));
if (mask != 0xffff)
return src + BSF(~mask);
src += 16;
}
while (src < src_end && *src == (uint8)v0)
src++;
return src;
}
static inline void CopyBytesFastOverflow(uint8 *dst, const uint8 *src, size_t n) {
uint8 *dst_end = dst + n;
do {
_mm_storeu_si128((__m128i*)dst, _mm_loadu_si128((__m128i*)src));
dst += 16, src += 16;
} while (dst < dst_end);
}
static inline uint8 *WriteShortLrlRle(uint8 *dst_b_ptr, uint lrl, uint rlel) {
if (lrl > 15) {
*--dst_b_ptr = 0, lrl -= 15;
*--dst_b_ptr = 16 * rlel | (15 - lrl);
} else if (rlel > 15) {
*--dst_b_ptr = 16 * (rlel >> 1) | (15 - lrl);
*--dst_b_ptr = 16 * (rlel - (rlel >> 1)) | 0xF;
} else {
*--dst_b_ptr = 16 * rlel | (15 - lrl);
}
return dst_b_ptr;
}
int EncodeArray_AdvRLE(uint8 *dst, uint8 *dst_end, const uint8 *src, int src_size, float speed_tradeoff, int platforms, float *cost_ptr, int opts, int level) {
const uint8 *src_end = src + src_size;
const uint8 *safe_end = src + (src_size >= 18 ? src_size - 18 : 0);
const uint8 *start = src;
uint8 *dst_b_ptr = dst_end;
uint8 *dst_f_ptr = dst + 1;
uint8 last_rle_byte = 0;
*dst = 0;
while (src < safe_end) {
const uint8 *first_rle = ScanForNextRLE3(src, safe_end);
if (first_rle >= safe_end)
break;
src = GetRLELength(first_rle, src_end, safe_end);
uint lrl = first_rle - start;
uint rlel = src - first_rle;
if (dst_b_ptr - dst_f_ptr < lrl + 18)
return -1;
if (*first_rle != last_rle_byte) {
if (rlel < 8)
continue;
last_rle_byte = *first_rle;
*--dst_b_ptr = 1;
*dst_f_ptr++ = last_rle_byte;
}
CopyBytesFastOverflow(dst_f_ptr, start, lrl);
dst_f_ptr += lrl;
start = src;
if ((lrl <= 30 && rlel <= 15) || (lrl <= 15 && rlel <= 30)) {
dst_b_ptr = WriteShortLrlRle(dst_b_ptr, lrl, rlel);
continue;
}
// handle very long literal lengths, lrl is always < 0x40 after this.
if (lrl >= 0x40) {
if (lrl < 0x4f)
*--dst_b_ptr = 0, lrl -= 15;
while (lrl >= 0x40) {
if (dst_b_ptr - dst_f_ptr < 4)
return -1;
uint n = std::min(0x700u, lrl >> 6);
*--dst_b_ptr = (uint8)(((n - 1) >> 8) + 2);
*--dst_b_ptr = (uint8)(n - 1);
lrl -= n << 6;
}
}
uint rle_big = rlel >> 7;
rlel &= 0x7f;
if (rlel >= 3 && ((lrl <= 30 && rlel <= 15) || (lrl <= 15 && rlel <= 30))) {
dst_b_ptr = WriteShortLrlRle(dst_b_ptr, lrl, rlel);
} else if (lrl | rlel) {
uint n = lrl | rlel << 6;
*--dst_b_ptr = (uint8)((n >> 8) + 16);
*--dst_b_ptr = (uint8)n;
}
while (rle_big) {
if (dst_b_ptr - dst_f_ptr < 2)
return -1;
uint n = std::min(0x700u, rle_big);
*--dst_b_ptr = (uint8)(((n - 1) >> 8) + 9);
*--dst_b_ptr = (uint8)(n - 1);
rle_big -= n;
}
}
uint lrl = src_end - start;
if (lrl) {
if (dst_b_ptr - dst_f_ptr < lrl + 16)
return -1;
memmove(dst_f_ptr, start, lrl);
dst_f_ptr += lrl;
if (lrl >= 0x40) {
if (lrl < 0x4f)
*--dst_b_ptr = 0, lrl -= 15;
while (lrl >= 0x40) {
if (dst_b_ptr - dst_f_ptr < 4)
return -1;
uint n = std::min(0x700u, lrl >> 6);
*--dst_b_ptr = (uint8)(((n - 1) >> 8) + 2);
*--dst_b_ptr = (uint8)(n - 1);
lrl -= n << 6;
}
}
if (lrl) {
*--dst_b_ptr = (uint8)((lrl >> 8) + 16);
*--dst_b_ptr = (uint8)lrl;
}
}
uint size_f = dst_f_ptr - (dst + 1);
uint size_b = dst_end - dst_b_ptr;
int mode = 0;
float cost = kInvalidCost;
int outbytes = 0;
uint8 *temp = NULL;
if (opts & kEntropyOpt_RLEEntropy) {
HistoU8 histo;
if (size_f >= 32 && size_b + size_f <= 0xc000) {
temp = new uint8[size_f];
CountBytesHistoU8(dst + 1, size_f, &histo);
if (GetHistoMax(histo) == size_f) {
cost = GetTime_Memset(platforms, size_f) * speed_tradeoff + 6;
temp[0] = dst[1];
mode = 3;
outbytes = 1;
} else {
float huff_cost = size_f + 1;
int huff_mode = 0;
int n = EncodeArray_Huff(temp, temp + size_f, dst + 1, size_f, histo, speed_tradeoff, platforms, &huff_cost, &huff_mode, opts, level);
if (n >= 0 && n < size_f) {
mode = huff_mode;
outbytes = n;
cost = huff_cost;
}
}
}
}
if (mode && cost < size_f + 1) {
WriteChunkHeader(dst, mode, size_f, outbytes);
memmove(dst + 5, temp, outbytes);
int after_compact = MakeCompactChunkHdr(dst, outbytes + 5, &cost);
memmove(dst + after_compact, dst_b_ptr, size_b);
outbytes = after_compact + size_b;
cost += size_b;
} else {
memmove(dst_f_ptr, dst_b_ptr, size_b);
outbytes = size_f + size_b + 1;
cost = outbytes;
}
*cost_ptr = cost + GetTime_AdvRLE(platforms, src_size) * speed_tradeoff + 5;
delete temp;
return outbytes;
}
class HuffBuilder {
public:
HuffBuilder();
void BuildCodeLens(const HistoU8 &histo, int src_size, int limit, bool use_package_merge);
enum {
kAlphabetSize = 256,
kMaxCodeLen = 16,
};
void WriteTableNew(BitWriter64<1> *bits);
void WriteTableOld(BitWriter64<1> *bits);
void AssignSyms();
struct Entry {
uint16 sym;
uint16 count;
bool operator<(const Entry &e) { return count < e.count; }
};
int num_symbols_, highest_sym_;
int max_code_len_, min_code_len_;
int numsyms_of_len_[kMaxCodeLen];
uint base_syms_[kMaxCodeLen + 1];
uint8 sym2len_[kAlphabetSize];
union {
Entry ents_[kAlphabetSize + 1]; // +1 to account for terminator
uint32 sym2bits_[kAlphabetSize];
};
private:
static const HistoU8*ScaleCounts(const HistoU8 &counts, HistoU8 *out_counts);
void LimitCodeLensPackageMerge(Entry *ents, const HistoU8 &histo, int limit);
void LimitCodeLensHeuristic(Entry *ents, const HistoU8 &histo, int limit, Entry *he);
void CalcNumsymsEtc();
};
HuffBuilder::HuffBuilder() {
}
const HistoU8 *HuffBuilder::ScaleCounts(const HistoU8 &histo, HistoU8 *out_counts) {
uint total_counts = 0, max_count = 0;
size_t best_index = 0;
for (size_t i = 0; i < 256; i++) {
total_counts += histo.count[i];
if (histo.count[i] > max_count) {
max_count = histo.count[i];
best_index = i;
}
}
if (total_counts <= 0xffff)
return &histo;
float ratio = (float)0xffff / total_counts;
uint new_total_counts = 0;
for (size_t i = 0; i < 256; i++) {
uint v = histo.count[i];
if (v) {
v = std::max(std::min((uint)(ratio * v + 0.5f), 65535u), 1u);
new_total_counts += v;
}
out_counts->count[i] = v;
}
if (new_total_counts > 0xffff) {
assert(out_counts->count[best_index] >= new_total_counts - 0xffff);
out_counts->count[best_index] -= new_total_counts - 0xffff;
}
return out_counts;
}
static void RadixSortEnts(HuffBuilder::Entry *begin, size_t num_syms) {
int counts[2][256] = { 0 };
for (size_t i = 0; i != num_syms; i++) {
counts[0][(uint8)(begin[i].count)]++;
counts[1][(uint8)(begin[i].count >> 8)]++;
}
int y_buf[256];
HuffBuilder::Entry syms[256];
size_t iteration = 0;
HuffBuilder::Entry *read = begin, *write = syms;
do {
int *count_cur = counts[iteration];
for (size_t i = 0, k = 0; k != num_syms; i++) {
y_buf[i] = k;
k += count_cur[i];
}
if (iteration == 0) {
for (size_t i = 0; i != num_syms; i++)
write[y_buf[read[i].count & 0xFF]++] = read[i];
} else {
if (*count_cur == num_syms) {
memmove(write, read, 4 * num_syms);
break;
} else {
for (size_t i = 0; i != num_syms; i++)
write[y_buf[read[i].count >> 8]++] = read[i];
}
}
read = syms, write = begin;
} while (++iteration < 2);
}
void HuffBuilder::BuildCodeLens(const HistoU8 &histo_in, int src_size, int limit, bool use_package_merge) {
HistoU8 scaled_counts;
memset(sym2len_, 0, sizeof(sym2len_));
memset(numsyms_of_len_, 0, sizeof(numsyms_of_len_));
// Rescale the counts so that the sum is 65535 or less to make it fit inside the uint16
const HistoU8 *histop = (src_size > 65535) ? ScaleCounts(histo_in, &scaled_counts) : &histo_in;
Entry *e = ents_, *ents = ents_;
for (size_t i = 0; i < kAlphabetSize; i++) {
if (histop->count[i]) {
e->count = (uint16)histop->count[i];
e->sym = (uint8)i;
e++;
}
}
uint n = e - ents;
num_symbols_ = n;
highest_sym_ = n ? e[-1].sym : 0;
if (n < 2)
return;
// use radix sort for long arrays?
if (n <= 32)
MySort(ents, e);
else
RadixSortEnts(ents, n);
// Inplace huffman table construction using moffat's algorithm
ents[0].count += ents[1].count;
unsigned int r = 0, s = 2, t;
for (t = 1; t < n - 1; t++) {
int sum;
if (s >= n || ents[r].count < ents[s].count) {
sum = ents[r].count;
ents[r].count = t;
r++;
} else {
sum = ents[s].count;
s++;
}
if (s >= n || (r < t && ents[r].count < ents[s].count)) {
sum += ents[r].count;
ents[r].count = t;
r++;
} else {
sum += ents[s].count;
s++;
}
ents[t].count = sum;
}
ents[(size_t)n - 2].count = 0;
for (t = n - 2; t--; )
ents[t].count = ents[ents[t].count].count + 1;
unsigned int a = 1, u = 0, d = 0, x = n - 1;
t = n - 2;
do {
while ((int)t >= 0 && ents[t].count == d)
u += 1, t -= 1;
for (; (int)a > (int)u; a--, x--)
ents[x].count = d;
a = 2 * u, d++, u = 0;
} while (a > 0);
int min_code_len = ents[(size_t)n - 1].count;
int max_code_len = ents[0].count;
if (max_code_len <= limit) {
// common case when it fits inside of limit
for (size_t i = 0; i != n; i++) {
unsigned len = ents[i].count;
sym2len_[ents[i].sym] = len;
numsyms_of_len_[len]++;
}
max_code_len_ = max_code_len;
min_code_len_ = min_code_len;
} else {
// Max code length too long, use slow limited package merge or fast heuristic
if (use_package_merge)
LimitCodeLensPackageMerge(ents, *histop, limit);
else
LimitCodeLensHeuristic(ents, *histop, limit, ents);
}
assert(max_code_len_ <= limit);
}
void HuffBuilder::LimitCodeLensPackageMerge(Entry *ents, const HistoU8 &histo, int limit) {
Entry *e = ents;
for (size_t i = 0; i < kAlphabetSize; i++) {
if (histo.count[i]) {
e->count = (uint16)histo.count[i];
e->sym = (uint16)i;
e++;
}
}
int num_symbols = e - ents;
num_symbols_ = num_symbols;
e->count = 0xFFFF;
if (num_symbols <= 32)
MySort(ents, e);
else
RadixSortEnts(ents, num_symbols);
int ents_per_codelen = 2 * (num_symbols - 1);
Entry *tempmem = new Entry[ents_per_codelen * (limit - 1)];
Entry *huffents[16];
huffents[0] = ents;
for (int i = 1; i < limit; i++)
huffents[i] = tempmem + (i - 1) * ents_per_codelen;
int numsyms[16] = { num_symbols };
for (int i = 1; i < limit; i++) {
int x = 0, k;
Entry *e = ents;
for (k = 0; k < ents_per_codelen; k++) {
int num = e->count, countsum;
if (x + 1 >= numsyms[i - 1] || (countsum = huffents[i - 1][x].count + huffents[i - 1][x + 1].count) > num) {
if (num == 0xFFFF)
break;
huffents[i][k].count = num;
huffents[i][k].sym = e->sym;
e++;
} else {
huffents[i][k].count = countsum;
huffents[i][k].sym = x | 0x8000;
x += 2;
}
}
numsyms[i] = k;
}
memset(sym2len_, 0, sizeof(sym2len_));
int loop_ctr = numsyms[limit - 1];
for (int i = limit - 1; i >= 0; i--) {
int loop_ctr_next = 0;
for (int j = 0; j < loop_ctr; j++) {
uint16 sym = huffents[i][j].sym;
if (sym & 0x8000)
loop_ctr_next = sym - 0x7FFE;
else
sym2len_[sym]++;
}
loop_ctr = loop_ctr_next;
}
CalcNumsymsEtc();
delete[] tempmem;
}
void HuffBuilder::CalcNumsymsEtc() {
memset(numsyms_of_len_, 0, sizeof(numsyms_of_len_));
for (size_t i = 0; i != 256; i++) {
if (sym2len_[i])
numsyms_of_len_[sym2len_[i]]++;
}
int min_len = 1;
while (!numsyms_of_len_[min_len])
min_len++;
min_code_len_ = min_len;
int max_len = 31;
while (!numsyms_of_len_[max_len])
max_len--;
max_code_len_ = max_len;
}
template<bool SoftRestriction>
static inline int FindSymbolToInc(int limit, int *B, uint32 *shifts, const HistoU8 &histo, uint64 kraft_sum, HuffBuilder::Entry *he) {
int best_idx = -1, best_score = 0x80000000;
for (int j = 1; j < limit; j++) {
if (B[j - 1] != B[j] &&
(!SoftRestriction || shifts[j + 1] < 2 * (uint)kraft_sum)) {
int score = -(int)(histo.count[he[B[j]].sym] << j);
if (score > best_score) {
best_score = score;
best_idx = B[j];
}
}
}
return best_idx;
}
template<bool SoftRestriction>
static inline int FindSymbolToDec(int limit, int *B, uint32 *shifts, const HistoU8 &histo, uint64 kraft_sum, HuffBuilder::Entry *he) {
int best_idx = -1, best_score = 0x80000000;
for (int j = 1; j < limit; j++) {
if (B[j] != B[j + 1] &&
(SoftRestriction ? (shifts[j + 1] < 2u * -(int)kraft_sum) : (kraft_sum + shifts[j + 1] <= 0x100000000ull))) {
int score = histo.count[he[B[j] - 1].sym] << (j + 1);
if (score > best_score) {
best_score = score;
best_idx = B[j] - 1;
}
}
}
return best_idx;
}
void HuffBuilder::LimitCodeLensHeuristic(Entry *ents, const HistoU8 &histo, int limit, Entry *he) {
limit = std::min(limit, 15);
uint32 shifts[16];
int B[18];
int q = limit + 1, best_idx;
for (int i = 0; i <= q; i++) {
shifts[i] = 1 << (32 - i);
}
int num_symbols = num_symbols_;
uint64 kraft_sum = 0;
B[q] = 0;
// Truncate code lengths that are too long
for (int i = 0; i < num_symbols; i++) {
int codelen = he[i].count;
if (codelen > limit)
he[i].count = codelen = limit;
kraft_sum += shifts[codelen];
while (q > codelen)
B[--q] = i;
}
while (q > 0)
B[--q] = num_symbols;
while (kraft_sum != 0x100000000ull) {
if (kraft_sum > 0x100000000ull) {
if ((best_idx = FindSymbolToInc<true>(limit, B, shifts, histo, kraft_sum, he)) >= 0) {
int count = he[best_idx].count++;
kraft_sum -= shifts[count + 1];
B[count]++;
continue;
}
break;
} else {
// kraft too low
int best_idx = FindSymbolToDec<true>(limit, B, shifts, histo, kraft_sum, he);
int count = he[best_idx].count--;
kraft_sum += shifts[count];
B[count - 1]--;
}
}
while (kraft_sum > 0x100000000ull) {
best_idx = FindSymbolToInc<false>(limit, B, shifts, histo, kraft_sum, he);
int count = he[best_idx].count++;
kraft_sum -= shifts[count + 1];
B[count]++;
}
while (kraft_sum < 0x100000000ull) {
int best_idx = FindSymbolToDec<false>(limit, B, shifts, histo, kraft_sum, he);
int count = he[best_idx].count--;
kraft_sum += shifts[count];
B[count - 1]--;
}
uint max_code_len = ents[0].count;
uint min_code_len = ents[num_symbols - 1].count;
for (size_t i = 0; i != num_symbols; i++) {
unsigned len = ents[i].count;
sym2len_[ents[i].sym] = len;
numsyms_of_len_[len]++;
}
max_code_len_ = max_code_len;
min_code_len_ = min_code_len;
}
uint GetSymbolRiceSpaceUsageForK(uint *histo, int histo_size, int k) {
uint result = 0;
for (int i = 0; i < histo_size; i++) {
if (histo[i])
result += histo[i] * ((i >> k) + k + 1);
}
return result;
}
int EncodeSymRange(uint8 *rice, uint8 *bits, uint8 *bitcount, int used_syms, int *range, int numrange) {
if (used_syms >= 256)
return 0;
int which = (*range == 0);
int num = (*range != 0) + 2 * ((numrange - 3) / 2);
range += (*range == 0);
for (int i = 0; i < num; i++) {
int v = range[i];
int ebit = ~which++ & 1;
v += (1 << ebit) - 1;
int nb = BSR(v >> ebit);
rice[i] = nb;
nb += ebit;
bits[i] = v & ((1 << nb) - 1);
bitcount[i] = (uint8)nb;
}
return num;
}
void WriteNumSymRange(BitWriter64<1> *bits, int num_symrange, int used_syms) {
if (used_syms == 256)
return;
int x = std::min(used_syms, 257 - used_syms);
int nb = BSR(2 * x - 1) + 1;
int base = (1 << nb) - 2 * x;
if (num_symrange >= base) {
bits->Write(num_symrange + base, nb);
} else {
bits->Write(num_symrange, nb - 1);
}
}
void WriteManyRiceCodes(BitWriter64<1> *bits, const uint8 *data, size_t num) {
BitWriter64<1> tmp = *bits;
for (size_t i = 0; i != num; i++) {
uint v = data[i];
for (; v >= 24; v -= 24)
tmp.Write(0, 24);
tmp.Write(1, v + 1);
}
*bits = tmp;
}
void SplitRiceLowBits(uint8 *rest, uint8 *forced_bits, const uint8 *input, size_t num, int k) {
uint8 mask = (1 << k) - 1;
for (size_t i = 0; i != num; i++) {
uint v = input[i];
forced_bits[i] = v & mask;
rest[i] = v >> k;
}
}
void WriteRiceLowBits(BitWriter64<1> *bits, const uint8 *data, size_t num, int k) {
if (k == 0)
return;
BitWriter64<1> tmp = *bits;
for (size_t i = 0; i != num; i++)
tmp.Write(data[i], k);
*bits = tmp;
}
void WriteSymRangeLowBits(BitWriter64<1> *bits, const uint8 *data, const uint8 *bitcount, size_t num) {
BitWriter64<1> tmp = *bits;
for (size_t i = 0; i != num; i++)
tmp.Write(data[i], bitcount[i]);
*bits = tmp;
}
void HuffBuilder::WriteTableNew(BitWriter64<1> *bits) {
int range[kAlphabetSize + 4], *range_cur;
int sym = 0;
int symlen_count = 0;
uint8 enc_symlen[256];
uint lencount[21] = { 0 };
while (sym < kAlphabetSize && sym2len_[sym] == 0)
sym++;
range_cur = range;
*range_cur++ = sym;
int avg_4x = 32;
while (sym < kAlphabetSize) {
int symstart = sym, len;
while (sym < kAlphabetSize && (len = sym2len_[sym]) != 0) {
sym++;
int t = len - ((avg_4x + 2) >> 2);
avg_4x += t;
uint32 x = EncodeZigZag32(t);
enc_symlen[symlen_count] = x;
lencount[x]++;
symlen_count++;
}
*range_cur++ = sym - symstart;