forked from rarten/ooz
-
Notifications
You must be signed in to change notification settings - Fork 1
/
kraken_impl.cpp
2351 lines (2045 loc) · 71.9 KB
/
kraken_impl.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
#include "stdafx.h"
#include "util.h"
#include "kraken_impl.h"
#include "mermaid_impl.h"
#include "leviathan_impl.h"
#include "lzna_impl.h"
#include "bitknit.h"
static void ReverseBitsArray2048(const byte *input, byte *output);
KrakenDecoder *Kraken_Create() {
size_t scratch_size = 0x6C000;
size_t memory_needed = sizeof(KrakenDecoder) + scratch_size;
KrakenDecoder *dec = (KrakenDecoder*)MallocAligned(memory_needed, 16);
memset(dec, 0, sizeof(KrakenDecoder));
dec->scratch_size = scratch_size;
dec->scratch = (byte*)(dec + 1);
return dec;
}
void Kraken_Destroy(KrakenDecoder *kraken) {
FreeAligned(kraken);
}
const byte *Kraken_ParseHeader(KrakenHeader *hdr, const byte *p) {
int b = p[0];
if ((b & 0xF) == 0xC) {
if (((b >> 4) & 3) != 0) return NULL;
hdr->restart_decoder = (b >> 7) & 1;
hdr->uncompressed = (b >> 6) & 1;
b = p[1];
hdr->decoder_type = b & 0x7F;
hdr->use_checksums = !!(b >> 7);
if (hdr->decoder_type != 6 && hdr->decoder_type != 10 && hdr->decoder_type != 5 && hdr->decoder_type != 11 && hdr->decoder_type != 12)
return NULL;
return p + 2;
}
return NULL;
}
const byte *Kraken_ParseQuantumHeader(KrakenQuantumHeader *hdr, const byte *p, bool use_checksum) {
uint32 v = (p[0] << 16) | (p[1] << 8) | p[2];
uint32 size = v & 0x3FFFF;
if (size != 0x3ffff) {
hdr->compressed_size = size + 1;
hdr->flag1 = (v >> 18) & 1;
hdr->flag2 = (v >> 19) & 1;
if (use_checksum) {
hdr->checksum = (p[3] << 16) | (p[4] << 8) | p[5];
return p + 6;
} else {
return p + 3;
}
}
v >>= 18;
if (v == 1) {
// memset
hdr->checksum = p[3];
hdr->compressed_size = 0;
hdr->whole_match_distance = 0;
return p + 4;
}
return NULL;
}
uint32 Kraken_GetCrc(UNUSED const byte *p, UNUSED size_t p_size) {
// TODO: implement
return 0;
}
//Gate this and raise an error until I can grok and re-implement a fallback in plain C.
#ifdef OODLE_ENABLE_AVX2
// Rearranges elements in the input array so that bits in the index
// get flipped. Used only by Kraken type 12.
#ifdef __GNUC__
// Tell GCC/clang that this is an AVX implementation, so it can resolve it at compile-time
__attribute((targets("default", "avx", "sse2")))
#endif
static void ReverseBitsArray2048(const byte *input, byte *output) {
static const uint8 offsets[32] = {
0, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0, 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0,
0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8, 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8
};
__m128i t0, t1, t2, t3, s0, s1, s2, s3;
int i, j;
for(i = 0; i != 32; i++) {
j = offsets[i];
t0 = _mm_unpacklo_epi8(_mm_loadl_epi64((const __m128i *)&input[j]),
_mm_loadl_epi64((const __m128i *)&input[j + 256]));
t1 = _mm_unpacklo_epi8(_mm_loadl_epi64((const __m128i *)&input[j + 512]),
_mm_loadl_epi64((const __m128i *)&input[j + 768]));
t2 = _mm_unpacklo_epi8(_mm_loadl_epi64((const __m128i *)&input[j + 1024]),
_mm_loadl_epi64((const __m128i *)&input[j + 1280]));
t3 = _mm_unpacklo_epi8(_mm_loadl_epi64((const __m128i *)&input[j + 1536]),
_mm_loadl_epi64((const __m128i *)&input[j + 1792]));
s0 = _mm_unpacklo_epi8(t0, t1);
s1 = _mm_unpacklo_epi8(t2, t3);
s2 = _mm_unpackhi_epi8(t0, t1);
s3 = _mm_unpackhi_epi8(t2, t3);
t0 = _mm_unpacklo_epi8(s0, s1);
t1 = _mm_unpacklo_epi8(s2, s3);
t2 = _mm_unpackhi_epi8(s0, s1);
t3 = _mm_unpackhi_epi8(s2, s3);
_mm_storel_epi64((__m128i *)&output[0], t0);
_mm_storeh_pi((__m64*)&output[1024], _mm_castsi128_ps(t0));
_mm_storel_epi64((__m128i *)&output[256], t1);
_mm_storeh_pi((__m64*)&output[1280], _mm_castsi128_ps(t1));
_mm_storel_epi64((__m128i *)&output[512], t2);
_mm_storeh_pi((__m64*)&output[1536], _mm_castsi128_ps(t2));
_mm_storel_epi64((__m128i *)&output[768], t3);
_mm_storeh_pi((__m64*)&output[1792], _mm_castsi128_ps(t3));
output += 8;
}
}
#else
#error AVX Function without a fallback implemenation
#endif
VECTORIZED
int Kraken_DecodeBytes_Type12(const byte *src, size_t src_size, byte *output, int output_size, int type) {
BitReader bits;
int half_output_size;
uint32 split_left, split_mid, split_right;
const byte *src_mid;
NewHuffLut huff_lut;
HuffReader hr;
HuffRevLut rev_lut;
const uint8 *src_end = src + src_size;
bits.bitpos = 24;
bits.bits = 0;
bits.p = src;
bits.p_end = src_end;
BitReader_Refill(&bits);
static const uint32 code_prefix_org[12] = { 0x0, 0x0, 0x2, 0x6, 0xE, 0x1E, 0x3E, 0x7E, 0xFE, 0x1FE, 0x2FE, 0x3FE };
uint32 code_prefix[12] = { 0x0, 0x0, 0x2, 0x6, 0xE, 0x1E, 0x3E, 0x7E, 0xFE, 0x1FE, 0x2FE, 0x3FE };
uint8 syms[1280];
int num_syms;
if (!BitReader_ReadBitNoRefill(&bits)) {
num_syms = Huff_ReadCodeLengthsOld(&bits, syms, code_prefix);
} else if (!BitReader_ReadBitNoRefill(&bits)) {
num_syms = Huff_ReadCodeLengthsNew(&bits, syms, code_prefix);
} else {
return -1;
}
if (num_syms < 1)
return -1;
src = bits.p - ((24 - bits.bitpos) / 8);
if (num_syms == 1) {
memset(output, syms[0], output_size);
return src - src_end;
}
if (!Huff_MakeLut(code_prefix_org, code_prefix, &huff_lut, syms))
return -1;
ReverseBitsArray2048(huff_lut.bits2len, rev_lut.bits2len);
ReverseBitsArray2048(huff_lut.bits2sym, rev_lut.bits2sym);
if (type == 1) {
if (src + 3 > src_end)
return -1;
split_mid = *(uint16*)src;
src += 2;
hr.output = output;
hr.output_end = output + output_size;
hr.src = src;
hr.src_end = src_end;
hr.src_mid_org = hr.src_mid = src + split_mid;
hr.src_bitpos = 0;
hr.src_bits = 0;
hr.src_mid_bitpos = 0;
hr.src_mid_bits = 0;
hr.src_end_bitpos = 0;
hr.src_end_bits = 0;
if (!Kraken_DecodeBytesCore(&hr, &rev_lut))
return -1;
} else {
if (src + 6 > src_end)
return -1;
half_output_size = (output_size + 1) >> 1;
split_mid = *(uint32*)src & 0xFFFFFF;
src += 3;
if (split_mid > (src_end - src))
return -1;
src_mid = src + split_mid;
split_left = *(uint16*)src;
src += 2;
if (src_mid - src < split_left + 2 || src_end - src_mid < 3)
return -1;
split_right = *(uint16*)src_mid;
if (src_end - (src_mid + 2) < split_right + 2)
return -1;
hr.output = output;
hr.output_end = output + half_output_size;
hr.src = src;
hr.src_end = src_mid;
hr.src_mid_org = hr.src_mid = src + split_left;
hr.src_bitpos = 0;
hr.src_bits = 0;
hr.src_mid_bitpos = 0;
hr.src_mid_bits = 0;
hr.src_end_bitpos = 0;
hr.src_end_bits = 0;
if (!Kraken_DecodeBytesCore(&hr, &rev_lut))
return -1;
hr.output = output + half_output_size;
hr.output_end = output + output_size;
hr.src = src_mid + 2;
hr.src_end = src_end;
hr.src_mid_org = hr.src_mid = src_mid + 2 + split_right;
hr.src_bitpos = 0;
hr.src_bits = 0;
hr.src_mid_bitpos = 0;
hr.src_mid_bits = 0;
hr.src_end_bitpos = 0;
hr.src_end_bits = 0;
if (!Kraken_DecodeBytesCore(&hr, &rev_lut))
return -1;
}
return (int)src_size;
}
static uint32 bitmasks[32] = {
0x1, 0x3, 0x7, 0xf, 0x1f, 0x3f, 0x7f, 0xff,
0x1ff, 0x3ff, 0x7ff, 0xfff, 0x1fff, 0x3fff, 0x7fff, 0xffff,
0x1ffff, 0x3ffff, 0x7ffff, 0xfffff, 0x1fffff, 0x3fffff, 0x7fffff,
0xffffff, 0x1ffffff, 0x3ffffff, 0x7ffffff, 0xfffffff, 0x1fffffff, 0x3fffffff, 0x7fffffff, 0xffffffff
};
int Kraken_DecodeMultiArray(const uint8 *src, const uint8 *src_end,
uint8 *dst, uint8 *dst_end,
uint8 **array_data, int *array_lens, int array_count,
int *total_size_out, bool force_memmove, uint8 *scratch, uint8 *scratch_end) {
const uint8 *src_org = src;
if (src_end - src < 4)
return -1;
int decoded_size;
int num_arrays_in_file = *src++;
if (!(num_arrays_in_file & 0x80))
return -1;
num_arrays_in_file &= 0x3f;
if (dst == scratch) {
// todo: ensure scratch space first?
scratch += (scratch_end - scratch - 0xc000) >> 1;
dst_end = scratch;
}
int total_size = 0;
if (num_arrays_in_file == 0) {
for (int i = 0; i < array_count; i++) {
uint8 *chunk_dst = dst;
int dec = Kraken_DecodeBytes(&chunk_dst, src, src_end, &decoded_size, dst_end - dst, force_memmove, scratch, scratch_end);
if (dec < 0)
return -1;
dst += decoded_size;
array_lens[i] = decoded_size;
array_data[i] = chunk_dst;
src += dec;
total_size += decoded_size;
}
*total_size_out = total_size;
return src - src_org; // not supported yet
}
uint8 *entropy_array_data[32];
uint32 entropy_array_size[32];
// First loop just decodes everything to scratch
uint8 *scratch_cur = scratch;
for(int i = 0; i < num_arrays_in_file; i++) {
uint8 *chunk_dst = scratch_cur;
int dec = Kraken_DecodeBytes(&chunk_dst, src, src_end, &decoded_size, scratch_end - scratch_cur, force_memmove, scratch_cur, scratch_end);
if (dec < 0)
return -1;
entropy_array_data[i] = chunk_dst;
entropy_array_size[i] = decoded_size;
scratch_cur += decoded_size;
total_size += decoded_size;
src += dec;
}
*total_size_out = total_size;
if (src_end - src < 3)
return -1;
int Q = *(uint16*)src;
src += 2;
int out_size;
if (Kraken_GetBlockSize(src, src_end, &out_size, total_size) < 0)
return -1;
int num_indexes = out_size;
int num_lens = num_indexes - array_count;
if (num_lens < 1)
return -1;
if (scratch_end - scratch_cur < num_indexes)
return -1;
uint8 *interval_lenlog2 = scratch_cur;
scratch_cur += num_indexes;
if (scratch_end - scratch_cur < num_indexes)
return -1;
uint8 *interval_indexes = scratch_cur;
scratch_cur += num_indexes;
if (Q & 0x8000) {
int size_out;
int n = Kraken_DecodeBytes(&interval_indexes, src, src_end, &size_out, num_indexes, false, scratch_cur, scratch_end);
if (n < 0 || size_out != num_indexes)
return -1;
src += n;
for (int i = 0; i < num_indexes; i++) {
int t = interval_indexes[i];
interval_lenlog2[i] = t >> 4;
interval_indexes[i] = t & 0xF;
}
num_lens = num_indexes;
} else {
int lenlog2_chunksize = num_indexes - array_count;
int size_out;
int n = Kraken_DecodeBytes(&interval_indexes, src, src_end, &size_out, num_indexes, false, scratch_cur, scratch_end);
if (n < 0 || size_out != num_indexes)
return -1;
src += n;
n = Kraken_DecodeBytes(&interval_lenlog2, src, src_end, &size_out, lenlog2_chunksize, false, scratch_cur, scratch_end);
if (n < 0 || size_out != lenlog2_chunksize)
return -1;
src += n;
for (int i = 0; i < lenlog2_chunksize; i++)
if (interval_lenlog2[i] > 16)
return -1;
}
if (scratch_end - scratch_cur < 4)
return -1;
scratch_cur = ALIGN_POINTER(scratch_cur, 4);
if (scratch_end - scratch_cur < num_lens * 4)
return -1;
uint32 *decoded_intervals = (uint32*)scratch_cur;
int varbits_complen = Q & 0x3FFF;
if (src_end - src < varbits_complen)
return -1;
const uint8 *f = src;
uint32 bits_f = 0;
int bitpos_f = 24;
const uint8 *src_end_actual = src + varbits_complen;
const uint8 *b = src_end_actual;
uint32 bits_b = 0;
int bitpos_b = 24;
int i;
for (i = 0; i + 2 <= num_lens; i += 2) {
bits_f |= _byteswap_ulong(*(uint32*)f) >> (24 - bitpos_f);
f += (bitpos_f + 7) >> 3;
bits_b |= ((uint32*)b)[-1] >> (24 - bitpos_b);
b -= (bitpos_b + 7) >> 3;
int numbits_f = interval_lenlog2[i + 0];
int numbits_b = interval_lenlog2[i + 1];
bits_f = _rotl(bits_f | 1, numbits_f);
bitpos_f += numbits_f - 8 * ((bitpos_f + 7) >> 3);
bits_b = _rotl(bits_b | 1, numbits_b);
bitpos_b += numbits_b - 8 * ((bitpos_b + 7) >> 3);
int value_f = bits_f & bitmasks[numbits_f];
bits_f &= ~bitmasks[numbits_f];
int value_b = bits_b & bitmasks[numbits_b];
bits_b &= ~bitmasks[numbits_b];
decoded_intervals[i + 0] = value_f;
decoded_intervals[i + 1] = value_b;
}
// read final one since above loop reads 2
if (i < num_lens) {
bits_f |= _byteswap_ulong(*(uint32*)f) >> (24 - bitpos_f);
int numbits_f = interval_lenlog2[i];
bits_f = _rotl(bits_f | 1, numbits_f);
int value_f = bits_f & bitmasks[numbits_f];
decoded_intervals[i + 0] = value_f;
}
if (interval_indexes[num_indexes - 1])
return -1;
int indi = 0, leni = 0, source;
int increment_leni = (Q & 0x8000) != 0;
for(int arri = 0; arri < array_count; arri++) {
array_data[arri] = dst;
if (indi >= num_indexes)
return -1;
while ((source = interval_indexes[indi++]) != 0) {
if (source > num_arrays_in_file)
return -1;
if (leni >= num_lens)
return -1;
int cur_len = decoded_intervals[leni++];
int bytes_left = entropy_array_size[source - 1];
if (cur_len > bytes_left || cur_len > dst_end - dst)
return -1;
uint8 *blksrc = entropy_array_data[source - 1];
entropy_array_size[source - 1] -= cur_len;
entropy_array_data[source - 1] += cur_len;
uint8 *dstx = dst;
dst += cur_len;
memcpy(dstx, blksrc, cur_len);
}
leni += increment_leni;
array_lens[arri] = dst - array_data[arri];
}
if (indi != num_indexes || leni != num_lens)
return -1;
for (int ii = 0; ii < num_arrays_in_file; ii++) {
if (entropy_array_size[ii])
return -1;
}
return src_end_actual - src_org;
}
int Krak_DecodeRecursive(const byte *src, size_t src_size, byte *output, int output_size, uint8 *scratch, uint8 *scratch_end) {
const uint8 *src_org = src;
byte *output_end = output + output_size;
const byte *src_end = src + src_size;
if (src_size < 6)
return -1;
int n = src[0] & 0x7f;
if (n < 2)
return -1;
if (!(src[0] & 0x80)) {
src++;
do {
int decoded_size;
int dec = Kraken_DecodeBytes(&output, src, src_end, &decoded_size, output_end - output, true, scratch, scratch_end);
if (dec < 0)
return -1;
output += decoded_size;
src += dec;
} while (--n);
if (output != output_end)
return -1;
return src - src_org;
} else {
uint8 *array_data;
int array_len, decoded_size;
int dec = Kraken_DecodeMultiArray(src, src_end, output, output_end, &array_data, &array_len, 1, &decoded_size, true, scratch, scratch_end);
if (dec < 0)
return -1;
output += decoded_size;
if (output != output_end)
return -1;
return dec;
}
}
VECTORIZED
int Krak_DecodeRLE(const byte *src, size_t src_size, byte *dst, int dst_size, uint8 *scratch, uint8 *scratch_end) {
if (src_size <= 1) {
if (src_size != 1)
return -1;
memset(dst, src[0], dst_size);
return 1;
}
uint8 *dst_end = dst + dst_size;
const uint8 *cmd_ptr = src + 1, *cmd_ptr_end = src + src_size;
// Unpack the first X bytes of the command buffer?
if (src[0]) {
uint8 *dst_ptr = scratch;
int dec_size;
int n = Kraken_DecodeBytes(&dst_ptr, src, src + src_size, &dec_size, scratch_end - scratch, true, scratch, scratch_end);
if (n <= 0)
return -1;
int cmd_len = src_size - n + dec_size;
if (cmd_len > scratch_end - scratch)
return -1;
memcpy(dst_ptr + dec_size, src + n, src_size - n);
cmd_ptr = dst_ptr;
cmd_ptr_end = &dst_ptr[cmd_len];
}
int rle_byte = 0;
while (cmd_ptr < cmd_ptr_end) {
uint32 cmd = cmd_ptr_end[-1];
if (cmd - 1 >= 0x2f) {
cmd_ptr_end--;
uint32 bytes_to_copy = (-1 - cmd) & 0xF;
uint32 bytes_to_rle = cmd >> 4;
if (dst_end - dst < bytes_to_copy + bytes_to_rle || cmd_ptr_end - cmd_ptr < bytes_to_copy)
return -1;
memcpy(dst, cmd_ptr, bytes_to_copy);
cmd_ptr += bytes_to_copy;
dst += bytes_to_copy;
memset(dst, rle_byte, bytes_to_rle);
dst += bytes_to_rle;
} else if (cmd >= 0x10) {
uint32 data = *(uint16*)(cmd_ptr_end - 2) - 4096;
cmd_ptr_end -= 2;
uint32 bytes_to_copy = data & 0x3F;
uint32 bytes_to_rle = data >> 6;
if (dst_end - dst < bytes_to_copy + bytes_to_rle || cmd_ptr_end - cmd_ptr < bytes_to_copy)
return -1;
memcpy(dst, cmd_ptr, bytes_to_copy);
cmd_ptr += bytes_to_copy;
dst += bytes_to_copy;
memset(dst, rle_byte, bytes_to_rle);
dst += bytes_to_rle;
} else if (cmd == 1) {
rle_byte = *cmd_ptr++;
cmd_ptr_end--;
} else if (cmd >= 9) {
uint32 bytes_to_rle = (*(uint16*)(cmd_ptr_end - 2) - 0x8ff) * 128;
cmd_ptr_end -= 2;
if (dst_end - dst < bytes_to_rle)
return -1;
memset(dst, rle_byte, bytes_to_rle);
dst += bytes_to_rle;
} else {
uint32 bytes_to_copy = (*(uint16*)(cmd_ptr_end - 2) - 511) * 64;
cmd_ptr_end -= 2;
if (cmd_ptr_end - cmd_ptr < bytes_to_copy || dst_end - dst < bytes_to_copy)
return -1;
memcpy(dst, cmd_ptr, bytes_to_copy);
dst += bytes_to_copy;
cmd_ptr += bytes_to_copy;
}
}
if (cmd_ptr_end != cmd_ptr)
return -1;
if (dst != dst_end)
return -1;
return src_size;
}
int Kraken_GetBlockSize(const uint8 *src, const uint8 *src_end, int *dest_size, int dest_capacity) {
const byte *src_org = src;
int src_size, dst_size;
if (src_end - src < 2)
return -1; // too few bytes
int chunk_type = (src[0] >> 4) & 0x7;
if (chunk_type == 0) {
if (src[0] >= 0x80) {
// In this mode, memcopy stores the length in the bottom 12 bits.
src_size = ((src[0] << 8) | src[1]) & 0xFFF;
src += 2;
} else {
if (src_end - src < 3)
return -1; // too few bytes
src_size = ((src[0] << 16) | (src[1] << 8) | src[2]);
if (src_size & ~0x3ffff)
return -1; // reserved bits must not be set
src += 3;
}
if (src_size > dest_capacity || src_end - src < src_size)
return -1;
*dest_size = src_size;
return src + src_size - src_org;
}
if (chunk_type >= 6)
return -1;
// In all the other modes, the initial bytes encode
// the src_size and the dst_size
if (src[0] >= 0x80) {
if (src_end - src < 3)
return -1; // too few bytes
// short mode, 10 bit sizes
uint32 bits = ((src[0] << 16) | (src[1] << 8) | src[2]);
src_size = bits & 0x3ff;
dst_size = src_size + ((bits >> 10) & 0x3ff) + 1;
src += 3;
} else {
// long mode, 18 bit sizes
if (src_end - src < 5)
return -1; // too few bytes
uint32 bits = ((src[1] << 24) | (src[2] << 16) | (src[3] << 8) | src[4]);
src_size = bits & 0x3ffff;
dst_size = (((bits >> 18) | (src[0] << 14)) & 0x3FFFF) + 1;
if (src_size >= dst_size)
return -1;
src += 5;
}
if (src_end - src < src_size || dst_size > dest_capacity)
return -1;
*dest_size = dst_size;
return src_size;
}
template<typename T> VECTORIZED void SimpleSort(T *p, T *pend) {
if (p != pend) {
for (T *lp = p + 1, *rp; lp != pend; lp++) {
T t = lp[0];
for (rp = lp; rp > p && t < rp[-1]; rp--)
rp[0] = rp[-1];
rp[0] = t;
}
}
}
VECTORIZED
bool Tans_DecodeTable(BitReader *bits, int L_bits, TansData *tans_data) {
BitReader_Refill(bits);
if (BitReader_ReadBitNoRefill(bits)) {
int Q = BitReader_ReadBitsNoRefill(bits, 3);
int num_symbols = BitReader_ReadBitsNoRefill(bits, 8) + 1;
if (num_symbols < 2)
return false;
int fluff = BitReader_ReadFluff(bits, num_symbols);
int total_rice_values = fluff + num_symbols;
uint8 rice[512 + 16];
BitReader2 br2;
// another bit reader...
br2.p = bits->p - ((uint)(24 - bits->bitpos + 7) >> 3);
br2.p_end = bits->p_end;
br2.bitpos = (bits->bitpos - 24) & 7;
if (!DecodeGolombRiceLengths(rice, total_rice_values, &br2))
return false;
memset(rice + total_rice_values, 0, 16);
// Switch back to other bitreader impl
bits->bitpos = 24;
bits->p = br2.p;
bits->bits = 0;
BitReader_Refill(bits);
bits->bits <<= br2.bitpos;
bits->bitpos += br2.bitpos;
HuffRange range[133];
fluff = Huff_ConvertToRanges(range, num_symbols, fluff, &rice[num_symbols], bits);
if (fluff < 0)
return false;
BitReader_Refill(bits);
uint32 L = 1 << L_bits;
uint8 *cur_rice_ptr = rice;
int average = 6;
uint somesum = 0;
uint8 *tanstable_A = tans_data->A;
uint32 *tanstable_B = tans_data->B;
for (int ri = 0; ri < fluff; ri++) {
int symbol = range[ri].symbol;
int num = range[ri].num;
do {
BitReader_Refill(bits);
int nextra = Q + *cur_rice_ptr++;
if (nextra > 15)
return false;
int v = BitReader_ReadBitsNoRefillZero(bits, nextra) + (1 << nextra) - (1 << Q);
int average_div4 = average >> 2;
int limit = 2 * average_div4;
if (v <= limit)
v = average_div4 + (-(v & 1) ^ ((uint32)v >> 1));
if (limit > v)
limit = v;
v += 1;
average += limit - average_div4;
*tanstable_A = symbol;
*tanstable_B = (symbol << 16) + v;
tanstable_A += (v == 1);
tanstable_B += v >= 2;
somesum += v;
symbol += 1;
} while (--num);
}
tans_data->A_used = tanstable_A - tans_data->A;
tans_data->B_used = tanstable_B - tans_data->B;
if (somesum != L)
return false;
return true;
} else {
bool seen[256];
memset(seen, 0, sizeof(seen));
uint32 L = 1 << L_bits;
int count = BitReader_ReadBitsNoRefill(bits, 3) + 1;
int bits_per_sym = BSR(L_bits) + 1;
int max_delta_bits = BitReader_ReadBitsNoRefill(bits, bits_per_sym);
if (max_delta_bits == 0 || max_delta_bits > L_bits)
return false;
uint8 *tanstable_A = tans_data->A;
uint32 *tanstable_B = tans_data->B;
int weight = 0;
int total_weights = 0;
do {
BitReader_Refill(bits);
int sym = BitReader_ReadBitsNoRefill(bits, 8);
if (seen[sym])
return false;
int delta = BitReader_ReadBitsNoRefill(bits, max_delta_bits);
weight += delta;
if (weight == 0)
return false;
seen[sym] = true;
if (weight == 1) {
*tanstable_A++ = sym;
} else {
*tanstable_B++ = (sym << 16) + weight;
}
total_weights += weight;
} while (--count);
BitReader_Refill(bits);
int sym = BitReader_ReadBitsNoRefill(bits, 8);
if (seen[sym])
return false;
if ((int)(L - total_weights) < weight || (int)(L - total_weights) <= 1)
return false;
*tanstable_B++ = (sym << 16) + (L - total_weights);
tans_data->A_used = tanstable_A - tans_data->A;
tans_data->B_used = tanstable_B - tans_data->B;
SimpleSort(tans_data->A, tanstable_A);
SimpleSort(tans_data->B, tanstable_B);
return true;
}
}
void Tans_InitLut(TansData *tans_data, int L_bits, TansLutEnt *lut) {
TansLutEnt *pointers[4];
int L = 1 << L_bits;
int a_used = tans_data->A_used;
uint slots_left_to_alloc = L - a_used;
uint sa = slots_left_to_alloc >> 2;
pointers[0] = lut;
uint sb = sa + ((slots_left_to_alloc & 3) > 0);
pointers[1] = lut + sb;
sb += sa + ((slots_left_to_alloc & 3) > 1);
pointers[2] = lut + sb;
sb += sa + ((slots_left_to_alloc & 3) > 2);
pointers[3] = lut + sb;
// Setup the single entrys with weight=1
{
TansLutEnt *lut_singles = lut + slots_left_to_alloc, le;
le.w = 0;
le.bits_x = L_bits;
le.x = (1 << L_bits) - 1;
for (int i = 0; i < a_used; i++) {
lut_singles[i] = le;
lut_singles[i].symbol = tans_data->A[i];
}
}
// Setup the entrys with weight >= 2
int weights_sum = 0;
for (uint i = 0; i < tans_data->B_used; i++) {
int weight = tans_data->B[i] & 0xffff;
int symbol = tans_data->B[i] >> 16;
if (weight > 4) {
uint32 sym_bits = BSR(weight);
int Z = L_bits - sym_bits;
TansLutEnt le;
le.symbol = symbol;
le.bits_x = Z;
le.x = (1 << Z) - 1;
le.w = (L - 1) & (weight << Z);
int what_to_add = 1 << Z;
int X = (1 << (sym_bits + 1)) - weight;
for (int j = 0; j < 4; j++) {
TansLutEnt *dst = pointers[j];
int Y = (weight + ((weights_sum - j - 1) & 3)) >> 2;
if (X >= Y) {
for(int n = Y; n; n--) {
*dst++ = le;
le.w += what_to_add;
}
X -= Y;
} else {
for (int n = X; n; n--) {
*dst++ = le;
le.w += what_to_add;
}
Z--;
what_to_add >>= 1;
le.bits_x = Z;
le.w = 0;
le.x >>= 1;
for (int n = Y - X; n; n--) {
*dst++ = le;
le.w += what_to_add;
}
X = weight;
}
pointers[j] = dst;
}
} else {
assert(weight > 0);
uint32 bits = ((1 << weight) - 1) << (weights_sum & 3);
bits |= (bits >> 4);
int n = weight, ww = weight;
do {
uint32 idx = BSF(bits);
bits &= bits - 1;
TansLutEnt *dst = pointers[idx]++;
dst->symbol = symbol;
uint32 weight_bits = BSR(ww);
dst->bits_x = L_bits - weight_bits;
dst->x = (1 << (L_bits - weight_bits)) - 1;
dst->w = (L - 1) & (ww++ << (L_bits - weight_bits));
} while (--n);
}
weights_sum += weight;
}
}
VECTORIZED
bool Tans_Decode(TansDecoderParams *params) {
TansLutEnt *lut = params->lut, *e;
uint8 *dst = params->dst, *dst_end = params->dst_end;
const uint8 *ptr_f = params->ptr_f, *ptr_b = params->ptr_b;
uint32 bits_f = params->bits_f, bits_b = params->bits_b;
int bitpos_f = params->bitpos_f, bitpos_b = params->bitpos_b;
uint32 state_0 = params->state_0, state_1 = params->state_1;
uint32 state_2 = params->state_2, state_3 = params->state_3;
uint32 state_4 = params->state_4;
if (ptr_f > ptr_b)
return false;
#define TANS_FORWARD_BITS() \
bits_f |= *(uint32 *)ptr_f << bitpos_f; \
ptr_f += (31 - bitpos_f) >> 3; \
bitpos_f |= 24;
#define TANS_FORWARD_ROUND(state) \
e = &lut[state]; \
*dst++ = e->symbol; \
bitpos_f -= e->bits_x; \
state = (bits_f & e->x) + e->w; \
bits_f >>= e->bits_x; \
if (dst >= dst_end) \
break;
#define TANS_BACKWARD_BITS() \
bits_b |= _byteswap_ulong(((uint32 *)ptr_b)[-1]) << bitpos_b; \
ptr_b -= (31 - bitpos_b) >> 3; \
bitpos_b |= 24;
#define TANS_BACKWARD_ROUND(state) \
e = &lut[state]; \
*dst++ = e->symbol; \
bitpos_b -= e->bits_x; \
state = (bits_b & e->x) + e->w; \
bits_b >>= e->bits_x; \
if (dst >= dst_end) \
break;
if (dst < dst_end) {
for (;;) {
TANS_FORWARD_BITS();
TANS_FORWARD_ROUND(state_0);
TANS_FORWARD_ROUND(state_1);
TANS_FORWARD_BITS();
TANS_FORWARD_ROUND(state_2);
TANS_FORWARD_ROUND(state_3);
TANS_FORWARD_BITS();
TANS_FORWARD_ROUND(state_4);
TANS_BACKWARD_BITS();
TANS_BACKWARD_ROUND(state_0);
TANS_BACKWARD_ROUND(state_1);
TANS_BACKWARD_BITS();
TANS_BACKWARD_ROUND(state_2);
TANS_BACKWARD_ROUND(state_3);
TANS_BACKWARD_BITS();
TANS_BACKWARD_ROUND(state_4);
}
}
if (ptr_b - ptr_f + (bitpos_f >> 3) + (bitpos_b >> 3) != 0)
return false;
uint32 states_or = state_0 | state_1 | state_2 | state_3 | state_4;
if (states_or & ~0xFF)
return false;
dst_end[0] = (uint8)state_0;
dst_end[1] = (uint8)state_1;
dst_end[2] = (uint8)state_2;
dst_end[3] = (uint8)state_3;
dst_end[4] = (uint8)state_4;
return true;
}
int Krak_DecodeTans(const byte *src, size_t src_size, byte *dst, int dst_size, uint8 *scratch, uint8 *scratch_end) {
if (src_size < 8 || dst_size < 5)
return -1;
const uint8 *src_end = src + src_size;
BitReader br;
TansData tans_data;
br.bitpos = 24;
br.bits = 0;
br.p = src;
br.p_end = src_end;
BitReader_Refill(&br);
// reserved bit
if (BitReader_ReadBitNoRefill(&br))
return -1;
int L_bits = BitReader_ReadBitsNoRefill(&br, 2) + 8;
if (!Tans_DecodeTable(&br, L_bits, &tans_data))
return -1;
src = br.p - (24 - br.bitpos) / 8;
if (src >= src_end)
return -1;
uint32 lut_space_required = ((sizeof(TansLutEnt) << L_bits) + 15) &~ 15;
if (lut_space_required > (scratch_end - scratch))
return -1;
TansDecoderParams params;
params.dst = dst;
params.dst_end = dst + dst_size - 5;
params.lut = (TansLutEnt *)ALIGN_POINTER(scratch, 16);
Tans_InitLut(&tans_data, L_bits, params.lut);
// Read out the initial state