forked from powzix/ooz
-
Notifications
You must be signed in to change notification settings - Fork 12
/
compr_kraken.cpp
1693 lines (1511 loc) · 62.4 KB
/
compr_kraken.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_kraken.h"
#include "compress.h"
#include "compr_util.h"
#include "compr_entropy.h"
#include <algorithm>
#include <memory>
#include "match_hasher.h"
#include "compr_match_finder.h"
struct KrakenRecentOffs {
KrakenRecentOffs() {
offs[4] = offs[5] = offs[6] = 8;
}
int offs[8];
};
struct KrakEncLz {
uint8 *lits_start;
uint8 *lits;
uint8 *sub_lits_start;
uint8 *sub_lits;
uint8 *tokens_start;
uint8 *tokens;
uint8 *u8_offs_start;
uint8 *u8_offs;
uint32 *u32_offs_start;
uint32 *u32_offs;
uint8 *lrl8_start;
uint8 *lrl8;
uint32 *len32_start;
uint32 *len32;
int src_len;
const uint8 *src_ptr;
int recent0;
int encode_flags;
};
static bool KrakIsMatchLongEnough(uint ml, uint offs) {
switch (ml) {
case 0:
case 1:
case 2: return false;
case 3: return offs < 0x4000;
case 4: return offs < 0x20000;
case 5: return offs < 0x100000;
case 6:
case 7: return offs < 0x400000;
default: return true;
}
}
enum IsRecent {
kOFFSET = 0,
kRECENT = 1,
};
struct Krak {
enum {
kMinBytesPerRound = 256,
kMaxBytesPerRound = 4096,
kRecentOffsetCount = 3,
};
struct Token {
int recent_offset0;
int litlen;
int matchlen;
int offset;
};
struct TokenArray {
Token *data;
int size, capacity;
};
struct State {
int best_bit_count;
int recent_offs[3];
int matchlen;
int litlen;
int quick_recent_matchlen_litlen;
int prev_state;
void Initialize() {
best_bit_count = 0;
recent_offs[0] = 8;
recent_offs[1] = 8;
recent_offs[2] = 8;
matchlen = 0;
litlen = 0;
prev_state = 0;
quick_recent_matchlen_litlen = 0;
}
};
struct CostModel {
int chunk_type;
int sub_or_copy_mask;
uint lit_cost[256];
uint token_cost[256];
int offs_encode_type;
uint offs_cost[256];
uint offs_lo_cost[256];
uint matchlen_cost[256];
};
struct Stats {
HistoU8 lit_raw;
HistoU8 lit_sub;
HistoU8 token;
HistoU8 matchlen;
int offs_encode_type;
HistoU8 offs;
HistoU8 offs_lo;
static void RescaleOne(HistoU8 *h) {
for (size_t i = 0; i != 256; i++)
h->count[i] = (h->count[i] >> 4) + 1;
}
static void Rescale(Stats *s) {
RescaleOne(&s->lit_raw);
RescaleOne(&s->lit_sub);
RescaleOne(&s->offs);
if (s->offs_encode_type > 1)
RescaleOne(&s->offs_lo);
RescaleOne(&s->token);
RescaleOne(&s->matchlen);
}
static void RescaleAddOne(HistoU8 *h, const HistoU8 *t) {
for (size_t i = 0; i != 256; i++)
h->count[i] = ((h->count[i] + t->count[i]) >> 5) + 1;
}
static void RescaleAdd(Stats *s, const Stats *t, bool chunk_type_same) {
if (chunk_type_same) {
RescaleAddOne(&s->lit_raw, &t->lit_raw);
RescaleAddOne(&s->lit_sub, &t->lit_sub);
} else {
RescaleOne(&s->lit_raw);
RescaleOne(&s->lit_sub);
}
RescaleAddOne(&s->token, &t->token);
RescaleAddOne(&s->matchlen, &t->matchlen);
if (s->offs_encode_type == t->offs_encode_type) {
RescaleAddOne(&s->offs, &t->offs);
if (s->offs_encode_type > 1)
RescaleAddOne(&s->offs_lo, &t->offs_lo);
} else {
s->offs = t->offs;
s->offs_lo = t->offs_lo;
s->offs_encode_type = t->offs_encode_type;
RescaleOne(&s->offs);
if (s->offs_encode_type > 1)
RescaleOne(&s->offs_lo);
}
}
static void ReduceIfHigh(Stats *s) {
// empty
}
static void Update(Stats *h, const uint8 *src, int pos, const Token *tokens, int num_token) {
enum {
kIncrement = 2
};
for (int i = 0; i < num_token; i++) {
const Token *t = &tokens[i];
int litlen = t->litlen;
int recent = t->recent_offset0;
for (int j = 0; j < litlen; j++) {
uint b = src[pos + j];
h->lit_raw.count[b] += kIncrement;
h->lit_sub.count[(uint8)(b - src[pos + j - recent])] += kIncrement;
}
pos += litlen + t->matchlen;
int length_field = litlen;
if (litlen >= 3) {
h->matchlen.count[std::min(litlen - 3, 255)] += kIncrement;
length_field = 3;
}
if (t->matchlen < 2) {
assert(t->matchlen >= 2);
continue;
}
uint offset = t->offset;
int recent_field;
if (t->offset <= 0) {
recent_field = -(int)offset;
} else {
recent_field = 3;
if (h->offs_encode_type == 0) {
if (offset >= 8388360) {
uint t = BSR(offset - 8322816) | 0xF0;
h->offs.count[t] += kIncrement;
} else {
uint t = ((offset - 8) & 0xF) + 16 * (BSR(offset - 8 + 256) - 8);
h->offs.count[t] += kIncrement;
}
} else if (h->offs_encode_type == 1) {
uint t = BSR(offset + 8) - 3;
uint u = 8 * t | (((offset + 8) >> t) ^ 8);
h->offs.count[u] += kIncrement;
} else {
uint ohi = offset / h->offs_encode_type, olo = offset % h->offs_encode_type;
uint t = BSR(ohi + 8) - 3;
uint u = 8 * t | (((ohi + 8) >> t) ^ 8);
h->offs.count[u] += kIncrement;
h->offs_lo.count[olo] += kIncrement;
}
}
int matchlen_field = t->matchlen - 2;
if (t->matchlen - 17 >= 0) {
h->matchlen.count[std::min(t->matchlen - 17, 255)] += kIncrement;
matchlen_field = 15;
}
int token_value = (matchlen_field << 2) + (recent_field << 6) + (length_field);
h->token.count[token_value] += kIncrement;
}
}
};
static void MakeCostModel(const Stats *h, CostModel *cm) {
ConvertHistoToCost(h->offs, cm->offs_cost, 36);
if (h->offs_encode_type > 1)
ConvertHistoToCost(h->offs_lo, cm->offs_lo_cost, 0);
ConvertHistoToCost(h->token, cm->token_cost, 18);
ConvertHistoToCost(h->matchlen, cm->matchlen_cost, 12);
if (cm->chunk_type == 1)
ConvertHistoToCost(h->lit_raw, cm->lit_cost, 0);
else
ConvertHistoToCost(h->lit_sub, cm->lit_cost, 0);
}
static __forceinline uint BitsForLitlen(CostModel &cost_model, int cur_litlen) {
if (cur_litlen < 3)
return 0;
if (cur_litlen - 3 >= 255) {
int v = BSR(((unsigned int)(cur_litlen - 3 - 255) >> 6) + 1);
return cost_model.matchlen_cost[255] + 32 * (2 * v + 7);
} else {
return cost_model.matchlen_cost[cur_litlen - 3];
}
}
static __forceinline uint BitsForLit(const uint8 *src, int pos, int recent, const CostModel &cm, int litidx) {
const uint8 *p = src + pos;
return cm.lit_cost[(uint8)(p[0] - (p[-recent] & cm.sub_or_copy_mask))];
}
static __forceinline uint BitsForLits(const uint8 *src, int pos, int num, int recent, const CostModel &cm, int litidx) {
const uint8 *p = src + pos;
uint sum = 0;
for (int i = 0; i < num; i++, p++)
sum += cm.lit_cost[(uint8)(p[0] - (p[-recent] & cm.sub_or_copy_mask))];
return sum;
}
static __forceinline bool CheckMatchValidLength(uint ml, uint offs) {
return (offs < 0x100000) || ((offs < 0x200000) ? (ml >= 5) : (offs < 0x400000) ? (ml >= 6) : (ml >= 8));
}
static __forceinline int GetMatchlengthQ(const uint8 *src, int offset, const uint8 *src_end, uint32 u32_at_cur) {
return ::GetMatchlengthQ(src, offset, src_end, u32_at_cur);
}
static __forceinline int GetMatchlengthMin2(const uint8 *src_ptr_cur, int offset, const uint8 *src_ptr_safe_end) {
return ::GetMatchlengthMin2(src_ptr_cur, offset, src_ptr_safe_end);
}
static __forceinline int BitsForToken(const CostModel &cost_model, int cur_matchlen, int cmd_offset, int recent_field, int length_field) {
if (cur_matchlen - 17 >= 0) {
int bits_for_matchlen;
if (cur_matchlen - 17 >= 255) {
int bsr = BSR(((unsigned int)(cur_matchlen - 17 - 255) >> 6) + 1);
bits_for_matchlen = cost_model.matchlen_cost[255] + 32 * (2 * bsr + 7);
} else {
bits_for_matchlen = cost_model.matchlen_cost[cur_matchlen - 17];
}
return cost_model.token_cost[(15 << 2) + (recent_field << 6) + length_field] + bits_for_matchlen;
} else {
return cost_model.token_cost[((cur_matchlen - 2) << 2) + (recent_field << 6) + length_field];
}
}
static uint BitsForOffset(const CostModel &cost_model, uint offs) {
if (cost_model.offs_encode_type == 0) {
if (offs >= 8388360) {
unsigned t = BSR(offs - 8322816) | 0xF0;
unsigned u = t - 224;
return cost_model.offs_cost[t] + 32 * u + 12;
} else {
unsigned t = ((offs - 8) & 0xF) + 16 * (BSR(offs - 8 + 256) - 8);
unsigned u = (t >> 4) + 4;
return cost_model.offs_cost[t] + 32 * u;
}
} else if (cost_model.offs_encode_type == 1) {
unsigned t = BSR(offs + 8) - 3;
unsigned u = 8 * t | (((offs + 8) >> t) ^ 8);
return cost_model.offs_cost[u] + 32 * (u >> 3);
} else {
unsigned ohi = offs / cost_model.offs_encode_type, olo = offs % cost_model.offs_encode_type;
unsigned t = BSR(ohi + 8) - 3;
unsigned u = 8 * t | (((ohi + 8) >> t) ^ 8);
return cost_model.offs_cost[u] + 32 * (u >> 3) + cost_model.offs_lo_cost[olo];
}
}
static __forceinline int GetRecentOffsetIndex(const int *arr, int offset) {
return (offset == arr[0]) ? 0 :
(offset == arr[1]) ? 1 :
(offset == arr[2]) ? 2 : -1;
}
};
static float GetTime_KrakenWriteBits(int platforms, int src_len, int tokens, int len8) {
return CombineCostComponents(platforms,
200.0f + src_len * 0.405f + tokens * 15.213f + len8 * 4.017f,
200.0f + src_len * 0.419f + tokens * 19.861f + len8 * 10.898f,
200.0f + src_len * 0.647f + tokens * 24.886f + len8 * 9.685f,
200.0f + src_len * 0.305f + tokens * 13.591f + len8 * 4.394f);
}
static double GetTime_KrakenLengths(int platforms, int len8, int len32) {
return CombineCostComponents(platforms,
42.933f + len8 * 0.478f + len32 * 21.527f,
36.646f + len8 * 0.746f + len32 * 32.345f,
115.731f + len8 * 0.815f + len32 * 36.682f,
48.796f + len8 * 0.453f + len32 * 20.770f);
}
static int Kraken_EncodeLzArrays(float *cost_ptr, int *chunk_type_ptr, Krak::Stats *stats,
uint8 *dst, uint8 *dst_end,
LzCoder *lzcoder, LzTemp *lztemp,
KrakEncLz *kl, int start_pos) {
uint8 *dst_org = dst;
if (stats)
memset(stats, 0, sizeof(*stats));
const uint8 *src_ptr = kl->src_ptr;
int src_len = kl->src_len;
int initial_bytes = start_pos == 0 ? 8 : 0;
for (int i = 0; i < initial_bytes; i++)
*dst++ = src_ptr[i];
int level = lzcoder->compression_level;
int flag_ignore_u32_length = 0;
int extra_size = 0;
assert((lzcoder->encode_flags & 1) == 0);
int num_lits = kl->lits - kl->lits_start;
float lit_cost = kInvalidCost;
float memcpy_cost = num_lits + 3;
if (num_lits < 32 || level <= -4) {
*chunk_type_ptr = 1;
int n = EncodeArrayU8_Memcpy(dst, dst_end, kl->lits_start, num_lits);
if (n < 0)
return src_len;
dst += n;
lit_cost = memcpy_cost;
} else {
HistoU8 lits_histo, litsub_histo;
bool has_litsub = (kl->sub_lits != kl->sub_lits_start);
CountBytesHistoU8(kl->lits_start, num_lits, &lits_histo);
if (has_litsub)
CountBytesHistoU8(kl->sub_lits_start, num_lits, &litsub_histo);
if (stats) {
stats->lit_raw = lits_histo;
if (has_litsub)
stats->lit_sub = litsub_histo;
}
int lit_n = -1;
bool skip_normal_lit = false;
if (has_litsub) {
float litsub_extra_cost = CombineCostComponents1(lzcoder->platforms, num_lits,
0.14399999f, 0.292f, 0.322f, 0.129f) * lzcoder->speed_tradeoff;
bool skip_litsub = (level < 6) && (GetHistoCostApprox(lits_histo, num_lits) * 0.125f <=
GetHistoCostApprox(litsub_histo, num_lits) * 0.125f + litsub_extra_cost);
if (!skip_litsub) {
*chunk_type_ptr = 0;
float litsub_cost = kInvalidCost;
lit_n = EncodeArrayU8WithHisto(dst, dst_end, kl->sub_lits_start, num_lits, litsub_histo,
lzcoder->entropy_opts, lzcoder->speed_tradeoff, lzcoder->platforms,
&litsub_cost, level);
litsub_cost += litsub_extra_cost;
if (lit_n > 0 && lit_n < num_lits && litsub_cost <= memcpy_cost) {
lit_cost = litsub_cost;
if (level < 6)
skip_normal_lit = true;
}
}
}
if (!skip_normal_lit) {
int n = EncodeArrayU8WithHisto(dst, dst_end, kl->lits_start, num_lits, lits_histo,
lzcoder->entropy_opts, lzcoder->speed_tradeoff, lzcoder->platforms,
&lit_cost, level);
if (n > 0) {
lit_n = n;
*chunk_type_ptr = 1;
}
}
if (lit_n < 0)
return src_len;
dst += lit_n;
}
float token_cost = kInvalidCost;
int n = EncodeArrayU8(dst, dst_end, kl->tokens_start, kl->tokens - kl->tokens_start,
lzcoder->entropy_opts, lzcoder->speed_tradeoff, lzcoder->platforms,
&token_cost, level, stats ? &stats->token : NULL);
if (n < 0)
return src_len;
dst += n;
int offs_encode_type = 0;
float offs_cost = kInvalidCost;
n = EncodeLzOffsets(dst, dst_end, kl->u8_offs_start, kl->u32_offs_start, kl->u8_offs - kl->u8_offs_start,
lzcoder->entropy_opts, lzcoder->speed_tradeoff, lzcoder->platforms,
&offs_cost, 8, (lzcoder->encode_flags & 4), &offs_encode_type, level,
stats ? &stats->offs : NULL, stats ? &stats->offs_lo : NULL);
if (n < 0)
return src_len;
dst += n;
if (stats)
stats->offs_encode_type = offs_encode_type;
float lrl8_cost = kInvalidCost;
n = EncodeArrayU8(dst, dst_end, kl->lrl8_start, kl->lrl8 - kl->lrl8_start,
lzcoder->entropy_opts, lzcoder->speed_tradeoff, lzcoder->platforms,
&lrl8_cost, level, stats ? &stats->matchlen : NULL);
if (n < 0)
return src_len;
dst += n;
int lrl_num = kl->lrl8 - kl->lrl8_start;
int offs_num = kl->u8_offs - kl->u8_offs_start;
int tok_num = kl->tokens - kl->tokens_start;
int required = std::max(lrl_num, offs_num) + lrl_num + num_lits + 4 * lrl_num + 6 * offs_num + tok_num + 16;
required = std::max(std::max(required, 2 * num_lits), num_lits + 2 * tok_num) + 0xd000;
int scratch_available = std::min(3 * src_len + 32 + 0xd000, 0x6C000);
if (required > scratch_available) {
assert(required <= scratch_available);
return src_len;
}
n = WriteLzOffsetBits(dst, dst_end, kl->u8_offs_start, kl->u32_offs_start, offs_num, offs_encode_type,
kl->len32_start, kl->len32 - kl->len32_start,
flag_ignore_u32_length, extra_size);
if (n < 0)
return src_len;
dst += n;
if (dst - dst_org >= src_len)
return src_len;
float bits_cost = GetTime_KrakenWriteBits(lzcoder->platforms, src_len, tok_num, lrl_num) *
lzcoder->speed_tradeoff + (initial_bytes + flag_ignore_u32_length + n);
float cost = token_cost + lit_cost + offs_cost + lrl8_cost + bits_cost;
*cost_ptr = GetTime_KrakenLengths(lzcoder->platforms, lrl_num, kl->len32 - kl->len32_start) *
lzcoder->speed_tradeoff + cost;
return dst - dst_org;
}
static void KrakEncLz_Init(KrakEncLz *kl, LzTemp *lztemp, int src_len, const uint8 *src_base, int encode_flags) {
kl->src_ptr = src_base;
kl->src_len = src_len;
size_t nlits = src_len + 8;
size_t ntokens = src_len / 2 + 8;
size_t nu8offs = src_len / 3;
size_t nu32offs = src_len / 3;
size_t nlen8 = src_len / 5;
size_t nlen32 = src_len / 256;
uint8 *p = (uint8*)lztemp->scratch0.Allocate(nlits * 2 + ntokens + nu8offs + nu32offs * 4 + nlen8 + nlen32 * 4 + 256);
kl->lits_start = kl->lits = p, p += nlits;
kl->sub_lits_start = kl->sub_lits = p, p += nlits;
kl->tokens_start = kl->tokens = p, p += ntokens;
kl->u8_offs = kl->u8_offs_start = p, p += nu8offs;
p = AlignPointer<uint8*>(p, 4);
kl->u32_offs = kl->u32_offs_start = (uint32*)p, p += nu32offs * 4;
kl->lrl8 = kl->lrl8_start = p, p += nlen8;
p = AlignPointer<uint8*>(p, 4);
kl->len32 = kl->len32_start = (uint32*)p;
kl->recent0 = 8;
kl->encode_flags = encode_flags;
}
static inline int KrakEnk_WriteMatchLen(KrakEncLz &kl, int ml) {
int ml_token = ml - 2;
if (ml_token >= 15) {
ml_token = 15;
if (ml >= 255 + 17) {
*kl.lrl8++ = 255;
*kl.len32++ = ml - 255 - 17;
} else {
*kl.lrl8++ = ml - 17;
}
}
return ml_token << 2;
}
template<bool DoSubtract>
static void KrakEnc_WriteLitsLong(KrakEncLz &kl, const uint8 *p, size_t len) {
if (DoSubtract) {
SubtractBytesUnsafe(kl.sub_lits, p, len, -kl.recent0);
kl.sub_lits += len;
}
uint8 *d = kl.lits, *d_end = d + len;
do {
*(uint32*)d = *(uint32*)p;
d += 4, p += 4;
} while (d < d_end);
kl.lits = d_end;
if (len >= 258) {
*kl.lrl8++ = 255;
*kl.len32++ = len - 258;
} else {
*kl.lrl8++ = (uint8)(len - 3);
}
}
template<bool DoSubtract>
static inline int KrakEnc_WriteLits(KrakEncLz &kl, const uint8 *p, size_t len) {
if (len == 0)
return 0;
if (len > 8) {
KrakEnc_WriteLitsLong<DoSubtract>(kl, p, len);
return 3;
}
uint8 *lrl8 = kl.lrl8;
*lrl8 = (uint8)(len - 3);
kl.lrl8 = (len >= 3) ? lrl8 + 1 : lrl8;
uint8 *ll = kl.lits;
*(uint64*)ll = *(uint64*)p;
kl.lits = ll + len;
if (DoSubtract) {
uint8 *sl = kl.sub_lits;
_mm_storel_epi64((__m128i *)sl, _mm_sub_epi8(_mm_loadl_epi64((const __m128i *)p),
_mm_loadl_epi64((const __m128i *)&p[-kl.recent0])));
kl.sub_lits = sl + len;
}
return std::min<int>(len, 3);
}
static inline void KrakEnc_WriteFarOffs(KrakEncLz &kl, uint32 offs) {
int bsr = BSR(offs - 8322816);
*kl.u8_offs++ = bsr | 0xf0;
*kl.u32_offs++ = offs;
}
static inline void KrakEnc_WriteNearOffs(KrakEncLz &kl, uint32 offs) {
int bsr = BSR(offs + 248);
*kl.u8_offs++ = ((offs - 8) & 0xF) | 16 * (bsr - 8);
*kl.u32_offs++ = offs;
}
static inline void KrakEnc_WriteOffs(KrakEncLz &kl, uint32 offs) {
if (offs >= 8388360)
KrakEnc_WriteFarOffs(kl, offs);
else
KrakEnc_WriteNearOffs(kl, offs);
}
template<bool DoRecent, bool DoSubtract>
static inline void KrakEnc_AddToken(KrakEncLz &kl, KrakenRecentOffs &recent, const uint8 *litstart, size_t litlen, int matchlen, int offs_or_recent) {
int token = KrakEnc_WriteLits<DoSubtract>(kl, litstart, litlen);
token += KrakEnk_WriteMatchLen(kl, matchlen);
if (offs_or_recent > 0) {
token += 3 << 6;
if (DoRecent) {
recent.offs[6] = recent.offs[5];
recent.offs[5] = recent.offs[4];
recent.offs[4] = offs_or_recent;
}
kl.recent0 = offs_or_recent;
KrakEnc_WriteOffs(kl, offs_or_recent);
} else {
if (DoRecent) {
size_t idx = -offs_or_recent;
assert(idx >= 0 && idx <= 2);
token += idx << 6;
int v = recent.offs[idx + 4];
recent.offs[idx + 4] = recent.offs[idx + 3];
recent.offs[idx + 3] = recent.offs[idx + 2];
recent.offs[4] = v;
kl.recent0 = v;
}
}
*kl.tokens++ = token;
}
template<bool DoSubtract>
static inline void KrakEnc_AddFinal(KrakEncLz &kl, const uint8 *p, const uint8 *pend) {
size_t len = pend - p;
if (len) {
memcpy(kl.lits, p, len);
kl.lits += len;
if (DoSubtract) {
SubtractBytes(kl.sub_lits, p, len, -kl.recent0);
kl.sub_lits += len;
}
}
}
template<int Level, typename Hasher>
int KrakenCompressVeryfast(LzCoder *coder, LzTemp *lztemp, MatchLenStorage *mls_unused,
const uint8 *src, int src_size,
uint8 *dst, uint8 *dst_end,
int start_pos, int *chunk_type_ptr, float *cost_ptr) {
enum {
SkipFactor = (Level >= 1) ? 5 : (Level >= -2) ? 4 : 3,
DoRecent = Level >= 1,
DoSubtract = Level >= -1,
};
*chunk_type_ptr = -1;
if (src_size <= 128)
return -1;
uint dict_size = coder->opts->dictionarySize > 0 && coder->opts->dictionarySize <= 0x40000000 ?
coder->opts->dictionarySize : 0x40000000;
KrakEncLz kl;
KrakEncLz_Init(&kl, lztemp, src_size, src, coder->encode_flags);
int initial_copy_bytes = (start_pos == 0) ? 8 : 0;
const uint8 *src_end_minus8 = src + src_size - 8;
const uint8 *src_end_minus16 = src + src_size - 16;
int skip = 1 << SkipFactor;
const uint8 *src_cur = src + initial_copy_bytes;
const uint8 *src_end = src + src_size;
const uint8 *litstart = src_cur;
Hasher *hasher = (Hasher*)coder->hasher;
KrakenRecentOffs recent;
int last_offs = -8;
const uint8 *src_base = hasher->src_base_;
uint64 hashmult = hasher->hashmult_;
typename Hasher::ElemType *hash_ptr = hasher->hash_ptr_, *hash;
int hashshift = 64 - hasher->hash_bits_;
const uint8 *src_cur_next;
while ((skip >> SkipFactor) < src_end_minus16 - src_cur) {
src_cur_next = src_cur + (skip >> SkipFactor);
if (Level >= 0) {
hash = &hash_ptr[(size_t)(*(uint64*)src_cur_next * hashmult >> hashshift)];
_mm_prefetch((char*)hash, _MM_HINT_T0);
}
hash = &hash_ptr[(size_t)(*(uint64*)src_cur * hashmult >> hashshift)];
uint32 u32_at_cur = *(uint32*)src_cur;
uint32 hashval = *hash;
*hash = src_cur - src_base;
int offs, offs_or_recent;
const uint8 *matchstart;
if (Level >= 1 && (uint16)u32_at_cur == *(uint16*)&src_cur[-recent.offs[5]]) {
offs = -recent.offs[5];
offs_or_recent = -1;
matchstart = src_cur;
src_cur += 2;
} else if (Level >= 1 && (uint16)u32_at_cur == *(uint16*)&src_cur[-recent.offs[6]]) {
offs = -recent.offs[6];
offs_or_recent = -2;
matchstart = src_cur;
src_cur += 2;
} else if (!((u32_at_cur ^ *(uint32*)&src_cur[last_offs]) & 0xffffff00)) {
src_cur += 1;
offs = last_offs;
offs_or_recent = 0;
matchstart = src_cur;
hash_ptr[(size_t)(*(uint64*)src_cur * hashmult >> hashshift)] = src_cur - src_base;
src_cur += 3;
} else {
offs_or_recent = (typename Hasher::ElemType)(src_cur - src_base - hashval);
if (u32_at_cur != *(uint32*)&src_cur[-offs_or_recent])
goto no_match;
if ((uint)(offs_or_recent - 8) < (uint)(dict_size - 8)) {
offs = -offs_or_recent;
} else if (u32_at_cur == *(uint32*)(src_cur - 8)) {
offs = -8;
offs_or_recent = 8;
} else {
no_match:
if (Level >= -2)
skip++;
else
skip = std::min<int>(skip + ((src_cur - litstart) >> 1), 296);
src_cur = src_cur_next;
continue;
}
// Reduce literal length and increase match length for bytes preceding the match.
if (Level >= -2) {
while (src_cur > litstart && (src_base - src_cur) < offs &&
src_cur[-1] == src_cur[offs - 1])
src_cur--;
}
matchstart = src_cur;
src_cur += 4;
}
// compute length of it
for (; src_cur < src_end - 8; src_cur += 4) {
uint32 v = *(uint32*)src_cur ^ *(uint32*)(src_cur + offs);
if (v != 0) {
src_cur += (BSF(v) >> 3);
break;
}
}
src_cur = std::min(src_cur, src_end - 8);
assert(matchstart >= litstart);
int ml = src_cur - matchstart;
KrakEnc_AddToken<DoRecent, DoSubtract>(kl, recent, litstart, matchstart - litstart, ml, offs_or_recent);
litstart = src_cur;
last_offs = offs;
if (src_cur >= src_end - 16)
break;
if (Level >= 0) {
for (int i = 1; i < ml; i *= 2)
hash_ptr[(size_t)(*(uint64*)(i + matchstart) * hashmult >> hashshift)] = i + matchstart - src_base;
}
skip = 1 << SkipFactor;
}
KrakEnc_AddFinal<DoSubtract>(kl, litstart, src_end);
return Kraken_EncodeLzArrays(cost_ptr, chunk_type_ptr, NULL, dst, dst_end, coder, lztemp, &kl, start_pos);
}
static __forceinline void KrakCheckRecentMatch(const uint8 *src, const uint8 *src_end, uint32 u32, KrakenRecentOffs &recent, int idx, int &best_ml, int &best_off) {
int ml = GetMatchlengthQ(src, recent.offs[4 + idx], src_end, u32);
if (ml > best_ml)
best_ml = ml, best_off = idx;
}
template<typename Hasher>
static __forceinline LengthAndOffset KrakenFast_GetMatch(const uint8 *cur_ptr, const uint8 *src_end_safe, const uint8 *lit_start,
KrakenRecentOffs &recent, Hasher *hasher,
const uint8 *next_cur_ptr, int dict_size, int min_match_length) {
typename Hasher::HashPos hp = hasher->GetHashPos(cur_ptr);
uint32 u32_at_src = *(uint32*)cur_ptr;
hasher->SetHashPosPrefetch(next_cur_ptr);
int recent_ml = 0, recent_off = -1;
KrakCheckRecentMatch(cur_ptr, src_end_safe, u32_at_src, recent, 0, recent_ml, recent_off);
KrakCheckRecentMatch(cur_ptr, src_end_safe, u32_at_src, recent, 1, recent_ml, recent_off);
KrakCheckRecentMatch(cur_ptr, src_end_safe, u32_at_src, recent, 2, recent_ml, recent_off);
int best_offs = 0, best_ml = 0;
// If we found a recent offset at least 4 bytes long then use it.
if (recent_ml >= 4) {
hasher->Insert(hp);
best_offs = -recent_off, best_ml = recent_ml;
} else {
// Make decompression faster by skipping short recent matches
if (cur_ptr - lit_start >= 56) {
if (recent_ml <= 2)
recent_ml = 0;
min_match_length = std::max(min_match_length, 5);
}
int max_ml = 0;
uint32 *cur_hash_ptr = hp.ptr1;
for (;;) {
for (size_t hashidx = 0; hashidx != Hasher::NumHash; hashidx++) {
if ((cur_hash_ptr[hashidx] & 0xfc000000) == (hp.hi & 0xfc000000)) {
int cur_offs = (hp.pos - cur_hash_ptr[hashidx]) & 0x3ffffff;
if (cur_offs < dict_size) {
cur_offs = std::max(cur_offs, 8);
if (*(uint32*)(cur_ptr - cur_offs) == u32_at_src &&
(max_ml < 4 || (cur_ptr + max_ml < src_end_safe && *(cur_ptr + max_ml) == *(cur_ptr + max_ml - cur_offs)))) {
int cur_ml = 4 + CountMatchingBytes(cur_ptr + 4, src_end_safe, cur_offs);
if (cur_ml > max_ml && cur_ml >= min_match_length) {
max_ml = cur_ml;
if (KrakIsMatchLongEnough(cur_ml, cur_offs) && IsMatchBetter(cur_ml, cur_offs, best_ml, best_offs))
best_offs = cur_offs, best_ml = cur_ml;
}
}
}
}
}
if (!Hasher::DualHash || cur_hash_ptr == hp.ptr2)
break;
cur_hash_ptr = hp.ptr2;
}
hasher->Insert(hp);
if (!IsBetterThanRecent(recent_ml, best_ml, best_offs))
best_offs = -recent_off, best_ml = recent_ml;
}
LengthAndOffset match = { best_ml, best_offs };
return match;
}
template<int NumHash, bool DualHash, int NumLazy>
int KrakenCompressFast(LzCoder *lzcoder, LzTemp *lztemp,
const uint8 *src, int src_len, uint8 *dst, uint8 *dst_end,
int start_pos, int *chunk_type_ptr, float *cost_ptr) {
const uint8 *src_end = src + src_len;
KrakEncLz kl;
KrakenRecentOffs recent;
*chunk_type_ptr = -1;
if (src_len <= 128)
return src_len;
int dict_size = lzcoder->opts->dictionarySize;
dict_size = (dict_size <= 0) ? 0x40000000 : std::min(dict_size, 0x40000000);
int min_match_length = std::max(lzcoder->opts->min_match_length, 4);
int initial_copy_bytes = (start_pos == 0) ? 8 : 0;
KrakEncLz_Init(&kl, lztemp, src_len, src, lzcoder->encode_flags);
int recent0 = 8;
const uint8 *cur_ptr = src + initial_copy_bytes, *litstart = cur_ptr;
typedef MatchHasher<NumHash, DualHash> Hasher;
Hasher *hasher = (Hasher *)lzcoder->hasher;
hasher->SetHashPos(cur_ptr);
uint skip = 256;
LengthAndOffset m;
for(;;) {
if ((NumHash == 1) && *(uint32*)(cur_ptr + 1) == *(uint32*)(cur_ptr + 1 - recent0)) {
int len = CountMatchingBytes(cur_ptr + 5, src_end - 8, recent0) + 4;
typename Hasher::HashPos hp = hasher->GetHashPos(cur_ptr);
hasher->SetHashPosPrefetch(cur_ptr + 2);
hasher->Insert(hp);
cur_ptr += 1;
m.offset = 0;
m.length = len;
} else {
uint increment = (NumHash == 1) ? skip >> 8 : 1;
const uint8 *next_ptr = cur_ptr + increment;
if (src_end - 16 - cur_ptr <= increment)
break;
m = KrakenFast_GetMatch(cur_ptr, src_end - 8, litstart, recent, hasher, next_ptr, dict_size, min_match_length);
if (m.length < 2) {
cur_ptr = next_ptr;
skip++;
continue;
}
if (NumLazy >= 1) {
while (cur_ptr + 1 < src_end - 16) {
LengthAndOffset m1 = KrakenFast_GetMatch(cur_ptr + 1, src_end - 8, litstart, recent, hasher, cur_ptr + 2, dict_size, min_match_length);
if (m1.length >= 2 && GetLazyScore(m1, m) > 0) {
cur_ptr += 1; // lazy1 is better
m = m1;
} else {
if (NumLazy < 2 || cur_ptr + 2 >= src_end - 16 || m.length == 2)
break;
LengthAndOffset m2 = KrakenFast_GetMatch(cur_ptr + 2, src_end - 8, litstart, recent, hasher, cur_ptr + 3, dict_size, min_match_length);
if (m2.length >= 2 && GetLazyScore(m2, m) > 3) {
cur_ptr += 2; // lazy2 is better
m = m2;
} else {
break;
}
}
}
}
}
assert(m.offset >= -2);
ptrdiff_t actual_offs = (m.offset <= 0) ? recent.offs[-m.offset + 4] : m.offset;
// Reduce literal length and increase match length for bytes preceding the match.
while (cur_ptr > litstart && cur_ptr - hasher->src_base_ > actual_offs && cur_ptr[-1] == cur_ptr[-actual_offs - 1])
cur_ptr--, m.length++;
if (m.offset == 0 && cur_ptr == litstart)
m.offset = -1;
KrakEnc_AddToken<true,true>(kl, recent, litstart, cur_ptr - litstart, m.length, m.offset);
cur_ptr += m.length;
litstart = cur_ptr;
if (cur_ptr >= src_end - 16)
break;
recent0 = kl.recent0;
hasher->InsertRange(cur_ptr - m.length, m.length);
skip = 256;
}
KrakEnc_AddFinal<true>(kl, litstart, src_end);
return Kraken_EncodeLzArrays(cost_ptr, chunk_type_ptr, NULL, dst, dst_end, lzcoder, lztemp, &kl, start_pos);
}
static LengthAndOffset KrakenGetLzMatch(const LengthAndOffset *matches, KrakenRecentOffs *recents,
const uint8 *src, const uint8 *src_end,
int min_match_len, int arg_14,
const uint8 *window_base, int max_match_offset) {
uint32 m32 = *(uint32*)src;
int best_ml = 0, best_offs = 0, ml;
LengthAndOffset result;
if ((ml = Krak::GetMatchlengthQ(src, recents->offs[4], src_end, m32)) > best_ml)
best_ml = ml, best_offs = 0;
if ((ml = Krak::GetMatchlengthQ(src, recents->offs[5], src_end, m32)) > best_ml)
best_ml = ml, best_offs = -1;
if ((ml = Krak::GetMatchlengthQ(src, recents->offs[6], src_end, m32)) > best_ml)
best_ml = ml, best_offs = -2;
if (best_ml < 4) {
if (arg_14 >= 56) {
if (best_ml <= 2)
best_ml = 0;
min_match_len++;
}
uint best_m_ml = 0, best_m_offs = 0;
for (size_t i = 0; i != 4; i++) {
uint ml = matches[i].length;
if (ml < min_match_len)
break;
if (ml > src_end - src && (ml = src_end - src) < min_match_len)
break;
uint offs = matches[i].offset;
if (offs >= max_match_offset)
continue;
// Since decoder copies in 64-bit chunks we cannot support copies
// that are longer than the offset, if offset is less than 8.
if (offs < 8) {
// Expand the offset to at least 8 bytes long
uint tt = offs;
do offs += tt; while (offs < 8);
// Check if it's a valid offset and still match
if (offs > src - window_base)
continue;
ml = GetMatchlengthQMin3(src, offs, src_end, m32);
if (ml < min_match_len)
continue;
}
if (KrakIsMatchLongEnough(ml, offs) && IsMatchBetter(ml, offs, best_m_ml, best_m_offs)) {
best_m_offs = offs;
best_m_ml = ml;
}
}
if (IsBetterThanRecent(best_ml, best_m_ml, best_m_offs)) {
best_ml = best_m_ml;
best_offs = best_m_offs;
}
}
result.length = best_ml;
result.offset = best_offs;
return result;
}
static int RunKrakenMatcherToGetStats(float *cost_ptr, int *chunk_type_ptr, Krak::Stats *stats,
uint8 *dst_ptr, uint8 *dst_end,
int min_match_len,
LzCoder *lzcoder, LengthAndOffset *lao,
const uint8 *src_ptr, int src_len, int start_pos, const uint8 *window_base,
LzTemp *lztemp) {
memset(stats, 0, sizeof(*stats));
KrakenRecentOffs recent;
KrakEncLz kl;
KrakEncLz_Init(&kl, lztemp, src_len, src_ptr, lzcoder->encode_flags);
int initial_copy_bytes = (start_pos == 0) ? 8 : 0;
int pos = initial_copy_bytes, last_pos = initial_copy_bytes;
int dict_size = lzcoder->opts->dictionarySize > 0 && lzcoder->opts->dictionarySize <= 0x40000000 ? lzcoder->opts->dictionarySize : 0x40000000;
while (pos < src_len - 16) {
LengthAndOffset m0 = KrakenGetLzMatch(&lao[4 * pos], &recent, &src_ptr[pos], &src_ptr[src_len - 8],
min_match_len, pos - last_pos, window_base, dict_size);
if (m0.length == 0) {
pos++;
continue;
}
while (pos + 1 < src_len - 16) {
LengthAndOffset m1 = KrakenGetLzMatch(&lao[4 * (pos + 1)], &recent, &src_ptr[pos + 1], &src_ptr[src_len - 8],
min_match_len, pos + 1 - last_pos, window_base, dict_size);
if (m1.length && GetLazyScore(m1, m0) > 0) {
pos++; // lazy1 is better