-
Notifications
You must be signed in to change notification settings - Fork 22
/
lzma2_enc.c
2099 lines (1862 loc) · 80.1 KB
/
lzma2_enc.c
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
/* lzma2_enc.c -- LZMA2 Encoder
Based on LzmaEnc.c and Lzma2Enc.c : Igor Pavlov
Modified for FL2 by Conor McCarthy
Public domain
*/
#include <stdlib.h>
#include <math.h>
#include "fl2_errors.h"
#include "fl2_internal.h"
#include "lzma2_enc.h"
#include "fl2_compress_internal.h"
#include "mem.h"
#include "count.h"
#include "radix_mf.h"
#include "range_enc.h"
#ifdef FL2_XZ_BUILD
# include "tuklib_integer.h"
# define MEM_readLE32(a) unaligned_read32le(a)
# ifdef TUKLIB_FAST_UNALIGNED_ACCESS
# define MEM_read16(a) (*(const U16*)(a))
# endif
#endif
#define kNumReps 4U
#define kNumStates 12U
#define kNumLiterals 0x100U
#define kNumLitTables 3U
#define kNumLenToPosStates 4U
#define kNumPosSlotBits 6U
#define kDicLogSizeMin 18U
#define kDicLogSizeMax 31U
#define kDistTableSizeMax (kDicLogSizeMax * 2U)
#define kNumAlignBits 4U
#define kAlignTableSize (1U << kNumAlignBits)
#define kAlignMask (kAlignTableSize - 1U)
#define kMatchRepriceFrequency 64U
#define kRepLenRepriceFrequency 64U
#define kStartPosModelIndex 4U
#define kEndPosModelIndex 14U
#define kNumPosModels (kEndPosModelIndex - kStartPosModelIndex)
#define kNumFullDistancesBits (kEndPosModelIndex >> 1U)
#define kNumFullDistances (1U << kNumFullDistancesBits)
#define kNumPositionBitsMax 4U
#define kNumPositionStatesMax (1U << kNumPositionBitsMax)
#define kNumLiteralContextBitsMax 4U
#define kNumLiteralPosBitsMax 4U
#define kLcLpMax 4U
#define kLenNumLowBits 3U
#define kLenNumLowSymbols (1U << kLenNumLowBits)
#define kLenNumHighBits 8U
#define kLenNumHighSymbols (1U << kLenNumHighBits)
#define kLenNumSymbolsTotal (kLenNumLowSymbols * 2 + kLenNumHighSymbols)
#define kMatchLenMin 2U
#define kMatchLenMax (kMatchLenMin + kLenNumSymbolsTotal - 1U)
#define kMatchesMax 65U /* Doesn't need to be larger than FL2_HYBRIDCYCLES_MAX + 1 */
#define kOptimizerEndSize 32U
#define kOptimizerBufferSize (kMatchLenMax * 2U + kOptimizerEndSize)
#define kOptimizerSkipSize 16U
#define kInfinityPrice (1UL << 30U)
#define kNullDist (U32)-1
#define kMaxMatchEncodeSize 20
#define kMaxChunkCompressedSize (1UL << 16U)
/* Need to leave sufficient space for expanded output from a full opt buffer with bad starting probs */
#define kChunkSize (kMaxChunkCompressedSize - 2048U)
#define kSqrtChunkSize 252U
/* Hard to define where the match table read pos definitely catches up with the output size, but
* 64 bytes of input expanding beyond 256 bytes right after an encoder reset is most likely impossible.
* The encoder will error out if this happens. */
#define kTempMinOutput 256U
#define kTempBufferSize (kTempMinOutput + kOptimizerBufferSize + kOptimizerBufferSize / 4U)
#define kMaxChunkUncompressedSize (1UL << 21U)
#define kChunkHeaderSize 5U
#define kChunkResetShift 5U
#define kChunkUncompressedDictReset 1U
#define kChunkUncompressed 2U
#define kChunkCompressedFlag 0x80U
#define kChunkNothingReset 0U
#define kChunkStateReset (1U << kChunkResetShift)
#define kChunkStatePropertiesReset (2U << kChunkResetShift)
#define kChunkAllReset (3U << kChunkResetShift)
#define kMaxHashDictBits 14U
#define kHash3Bits 14U
#define kNullLink -1
#define kMinTestChunkSize 0x4000U
#define kRandomFilterMarginBits 8U
#define kState_LitAfterMatch 4
#define kState_LitAfterRep 5
#define kState_MatchAfterLit 7
#define kState_RepAfterLit 8
static const BYTE kLiteralNextStates[kNumStates] = { 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 4, 5 };
#define LIT_NEXT_STATE(s) kLiteralNextStates[s]
static const BYTE kMatchNextStates[kNumStates] = { 7, 7, 7, 7, 7, 7, 7, 10, 10, 10, 10, 10 };
#define MATCH_NEXT_STATE(s) kMatchNextStates[s]
static const BYTE kRepNextStates[kNumStates] = { 8, 8, 8, 8, 8, 8, 8, 11, 11, 11, 11, 11 };
#define REP_NEXT_STATE(s) kRepNextStates[s]
static const BYTE kShortRepNextStates[kNumStates] = { 9, 9, 9, 9, 9, 9, 9, 11, 11, 11, 11, 11 };
#define SHORT_REP_NEXT_STATE(s) kShortRepNextStates[s]
#include "fastpos_table.h"
#include "radix_get.h"
/* Probabilities and prices for encoding match lengths.
* Two objects of this type are needed, one for normal matches
* and another for rep matches.
*/
typedef struct
{
size_t table_size;
unsigned prices[kNumPositionStatesMax][kLenNumSymbolsTotal];
LZMA2_prob choice; /* low[0] is choice_2. Must be consecutive for speed */
LZMA2_prob low[kNumPositionStatesMax << (kLenNumLowBits + 1)];
LZMA2_prob high[kLenNumHighSymbols];
} LZMA2_lenStates;
/* All probabilities for the encoder. This is a separate from the encoder object
* so the state can be saved and restored in case a chunk is not compressible.
*/
typedef struct
{
/* Fields are ordered for speed */
LZMA2_lenStates rep_len_states;
LZMA2_prob is_rep0_long[kNumStates][kNumPositionStatesMax];
size_t state;
U32 reps[kNumReps];
LZMA2_prob is_match[kNumStates][kNumPositionStatesMax];
LZMA2_prob is_rep[kNumStates];
LZMA2_prob is_rep_G0[kNumStates];
LZMA2_prob is_rep_G1[kNumStates];
LZMA2_prob is_rep_G2[kNumStates];
LZMA2_lenStates len_states;
LZMA2_prob dist_slot_encoders[kNumLenToPosStates][1 << kNumPosSlotBits];
LZMA2_prob dist_align_encoders[1 << kNumAlignBits];
LZMA2_prob dist_encoders[kNumFullDistances - kEndPosModelIndex];
LZMA2_prob literal_probs[(kNumLiterals * kNumLitTables) << kLcLpMax];
} LZMA2_encStates;
/*
* Linked list item for optimal parsing
*/
typedef struct
{
size_t state;
U32 price;
unsigned extra; /* 0 : normal
* 1 : LIT : MATCH
* > 1 : MATCH (extra-1) : LIT : REP0 (len) */
unsigned len;
U32 dist;
U32 reps[kNumReps];
} LZMA2_node;
#define MARK_LITERAL(node) (node).dist = kNullDist; (node).extra = 0;
#define MARK_SHORT_REP(node) (node).dist = 0; (node).extra = 0;
/*
* Table and chain for 3-byte hash. Extra elements in hash_chain_3 are malloced.
*/
typedef struct {
S32 table_3[1 << kHash3Bits];
S32 hash_chain_3[1];
} LZMA2_hc3;
/*
* LZMA2 encoder.
*/
struct LZMA2_ECtx_s
{
unsigned lc;
unsigned lp;
unsigned pb;
unsigned fast_length;
size_t len_end_max;
size_t lit_pos_mask;
size_t pos_mask;
unsigned match_cycles;
FL2_strategy strategy;
RC_encoder rc;
/* Finish writing the chunk at this size */
size_t chunk_size;
/* Don't encode a symbol beyond this limit (used by fast mode) */
size_t chunk_limit;
LZMA2_encStates states;
unsigned match_price_count;
unsigned rep_len_price_count;
size_t dist_price_table_size;
unsigned align_prices[kAlignTableSize];
unsigned dist_slot_prices[kNumLenToPosStates][kDistTableSizeMax];
unsigned distance_prices[kNumLenToPosStates][kNumFullDistances];
RMF_match base_match; /* Allows access to matches[-1] in LZMA_optimalParse */
RMF_match matches[kMatchesMax];
size_t match_count;
LZMA2_node opt_buf[kOptimizerBufferSize];
LZMA2_hc3* hash_buf;
ptrdiff_t chain_mask_2;
ptrdiff_t chain_mask_3;
ptrdiff_t hash_dict_3;
ptrdiff_t hash_prev_index;
ptrdiff_t hash_alloc_3;
/* Temp output buffer before space frees up in the match table */
BYTE out_buf[kTempBufferSize];
};
LZMA2_ECtx* LZMA2_createECtx(void)
{
LZMA2_ECtx *const enc = malloc(sizeof(LZMA2_ECtx));
DEBUGLOG(3, "LZMA2_createECtx");
if (enc == NULL)
return NULL;
enc->lc = 3;
enc->lp = 0;
enc->pb = 2;
enc->fast_length = 48;
enc->len_end_max = kOptimizerBufferSize - 1;
enc->lit_pos_mask = (1 << enc->lp) - 1;
enc->pos_mask = (1 << enc->pb) - 1;
enc->match_cycles = 1;
enc->strategy = FL2_ultra;
enc->match_price_count = 0;
enc->rep_len_price_count = 0;
enc->dist_price_table_size = kDistTableSizeMax;
enc->hash_buf = NULL;
enc->hash_dict_3 = 0;
enc->chain_mask_3 = 0;
enc->hash_alloc_3 = 0;
return enc;
}
void LZMA2_freeECtx(LZMA2_ECtx *const enc)
{
if (enc == NULL)
return;
free(enc->hash_buf);
free(enc);
}
#define LITERAL_PROBS(enc, pos, prev_symbol) (enc->states.literal_probs + ((((pos) & enc->lit_pos_mask) << enc->lc) + ((prev_symbol) >> (8 - enc->lc))) * kNumLiterals * kNumLitTables)
#define LEN_TO_DIST_STATE(len) (((len) < kNumLenToPosStates + 1) ? (len) - 2 : kNumLenToPosStates - 1)
#define IS_LIT_STATE(state) ((state) < 7)
HINT_INLINE
unsigned LZMA_getRepLen1Price(LZMA2_ECtx* const enc, size_t const state, size_t const pos_state)
{
unsigned const rep_G0_prob = enc->states.is_rep_G0[state];
unsigned const rep0_long_prob = enc->states.is_rep0_long[state][pos_state];
return GET_PRICE_0(rep_G0_prob) + GET_PRICE_0(rep0_long_prob);
}
static unsigned LZMA_getRepPrice(LZMA2_ECtx* const enc, size_t const rep_index, size_t const state, size_t const pos_state)
{
unsigned price;
unsigned const rep_G0_prob = enc->states.is_rep_G0[state];
if (rep_index == 0) {
unsigned const rep0_long_prob = enc->states.is_rep0_long[state][pos_state];
price = GET_PRICE_0(rep_G0_prob);
price += GET_PRICE_1(rep0_long_prob);
}
else {
unsigned const rep_G1_prob = enc->states.is_rep_G1[state];
price = GET_PRICE_1(rep_G0_prob);
if (rep_index == 1) {
price += GET_PRICE_0(rep_G1_prob);
}
else {
unsigned const rep_G2_prob = enc->states.is_rep_G2[state];
price += GET_PRICE_1(rep_G1_prob);
price += GET_PRICE(rep_G2_prob, rep_index - 2);
}
}
return price;
}
static unsigned LZMA_getRepMatch0Price(LZMA2_ECtx *const enc, size_t const len, size_t const state, size_t const pos_state)
{
unsigned const rep_G0_prob = enc->states.is_rep_G0[state];
unsigned const rep0_long_prob = enc->states.is_rep0_long[state][pos_state];
return enc->states.rep_len_states.prices[pos_state][len - kMatchLenMin]
+ GET_PRICE_0(rep_G0_prob)
+ GET_PRICE_1(rep0_long_prob);
}
static unsigned LZMA_getLiteralPriceMatched(const LZMA2_prob *const prob_table, U32 symbol, unsigned match_byte)
{
unsigned price = 0;
unsigned offs = 0x100;
symbol |= 0x100;
do {
match_byte <<= 1;
price += GET_PRICE(prob_table[offs + (match_byte & offs) + (symbol >> 8)], (symbol >> 7) & 1);
symbol <<= 1;
offs &= ~(match_byte ^ symbol);
} while (symbol < 0x10000);
return price;
}
HINT_INLINE
void LZMA_encodeLiteral(LZMA2_ECtx *const enc, size_t const pos, U32 symbol, unsigned const prev_symbol)
{
RC_encodeBit0(&enc->rc, &enc->states.is_match[enc->states.state][pos & enc->pos_mask]);
enc->states.state = LIT_NEXT_STATE(enc->states.state);
LZMA2_prob* const prob_table = LITERAL_PROBS(enc, pos, prev_symbol);
symbol |= 0x100;
do {
RC_encodeBit(&enc->rc, prob_table + (symbol >> 8), symbol & (1 << 7));
symbol <<= 1;
} while (symbol < 0x10000);
}
HINT_INLINE
void LZMA_encodeLiteralMatched(LZMA2_ECtx *const enc, const BYTE* const data_block, size_t const pos, U32 symbol)
{
RC_encodeBit0(&enc->rc, &enc->states.is_match[enc->states.state][pos & enc->pos_mask]);
enc->states.state = LIT_NEXT_STATE(enc->states.state);
unsigned match_symbol = data_block[pos - enc->states.reps[0] - 1];
LZMA2_prob* const prob_table = LITERAL_PROBS(enc, pos, data_block[pos - 1]);
unsigned offset = 0x100;
symbol |= 0x100;
do {
match_symbol <<= 1;
size_t prob_index = offset + (match_symbol & offset) + (symbol >> 8);
RC_encodeBit(&enc->rc, prob_table + prob_index, symbol & (1 << 7));
symbol <<= 1;
offset &= ~(match_symbol ^ symbol);
} while (symbol < 0x10000);
}
HINT_INLINE
void LZMA_encodeLiteralBuf(LZMA2_ECtx *const enc, const BYTE* const data_block, size_t const pos)
{
U32 const symbol = data_block[pos];
if (IS_LIT_STATE(enc->states.state)) {
unsigned const prev_symbol = data_block[pos - 1];
LZMA_encodeLiteral(enc, pos, symbol, prev_symbol);
}
else {
LZMA_encodeLiteralMatched(enc, data_block, pos, symbol);
}
}
static void LZMA_lengthStates_SetPrices(const LZMA2_prob *probs, U32 start_price, unsigned *prices)
{
for (size_t i = 0; i < 8; i += 2) {
U32 prob = probs[4 + (i >> 1)];
U32 price = start_price + GET_PRICE(probs[1], (i >> 2))
+ GET_PRICE(probs[2 + (i >> 2)], (i >> 1) & 1);
prices[i] = price + GET_PRICE_0(prob);
prices[i + 1] = price + GET_PRICE_1(prob);
}
}
FORCE_NOINLINE
static void LZMA_lengthStates_updatePrices(LZMA2_ECtx *const enc, LZMA2_lenStates* const ls)
{
U32 b;
{
unsigned const prob = ls->choice;
U32 a, c;
b = GET_PRICE_1(prob);
a = GET_PRICE_0(prob);
c = b + GET_PRICE_0(ls->low[0]);
for (size_t pos_state = 0; pos_state <= enc->pos_mask; pos_state++) {
unsigned *const prices = ls->prices[pos_state];
const LZMA2_prob *const probs = ls->low + (pos_state << (1 + kLenNumLowBits));
LZMA_lengthStates_SetPrices(probs, a, prices);
LZMA_lengthStates_SetPrices(probs + kLenNumLowSymbols, c, prices + kLenNumLowSymbols);
}
}
size_t i = ls->table_size;
if (i > kLenNumLowSymbols * 2) {
const LZMA2_prob *const probs = ls->high;
unsigned *const prices = ls->prices[0] + kLenNumLowSymbols * 2;
i = (i - (kLenNumLowSymbols * 2 - 1)) >> 1;
b += GET_PRICE_1(ls->low[0]);
do {
--i;
size_t sym = i + (1 << (kLenNumHighBits - 1));
U32 price = b;
do {
size_t bit = sym & 1;
sym >>= 1;
price += GET_PRICE(probs[sym], bit);
} while (sym >= 2);
unsigned const prob = probs[i + (1 << (kLenNumHighBits - 1))];
prices[i * 2] = price + GET_PRICE_0(prob);
prices[i * 2 + 1] = price + GET_PRICE_1(prob);
} while (i);
size_t const size = (ls->table_size - kLenNumLowSymbols * 2) * sizeof(ls->prices[0][0]);
for (size_t pos_state = 1; pos_state <= enc->pos_mask; pos_state++)
memcpy(ls->prices[pos_state] + kLenNumLowSymbols * 2, ls->prices[0] + kLenNumLowSymbols * 2, size);
}
}
/* Rare enough that not inlining is faster overall */
FORCE_NOINLINE
static void LZMA_encodeLength_MidHigh(LZMA2_ECtx *const enc, LZMA2_lenStates* const len_prob_table, unsigned const len, size_t const pos_state)
{
RC_encodeBit1(&enc->rc, &len_prob_table->choice);
if (len < kLenNumLowSymbols * 2) {
RC_encodeBit0(&enc->rc, &len_prob_table->low[0]);
RC_encodeBitTree(&enc->rc, len_prob_table->low + kLenNumLowSymbols + (pos_state << (1 + kLenNumLowBits)), kLenNumLowBits, len - kLenNumLowSymbols);
}
else {
RC_encodeBit1(&enc->rc, &len_prob_table->low[0]);
RC_encodeBitTree(&enc->rc, len_prob_table->high, kLenNumHighBits, len - kLenNumLowSymbols * 2);
}
}
HINT_INLINE
void LZMA_encodeLength(LZMA2_ECtx *const enc, LZMA2_lenStates* const len_prob_table, unsigned len, size_t const pos_state)
{
len -= kMatchLenMin;
if (len < kLenNumLowSymbols) {
RC_encodeBit0(&enc->rc, &len_prob_table->choice);
RC_encodeBitTree(&enc->rc, len_prob_table->low + (pos_state << (1 + kLenNumLowBits)), kLenNumLowBits, len);
}
else {
LZMA_encodeLength_MidHigh(enc, len_prob_table, len, pos_state);
}
}
FORCE_NOINLINE
static void LZMA_encodeRepMatchShort(LZMA2_ECtx *const enc, size_t const pos_state)
{
DEBUGLOG(7, "LZMA_encodeRepMatchShort");
RC_encodeBit1(&enc->rc, &enc->states.is_match[enc->states.state][pos_state]);
RC_encodeBit1(&enc->rc, &enc->states.is_rep[enc->states.state]);
RC_encodeBit0(&enc->rc, &enc->states.is_rep_G0[enc->states.state]);
RC_encodeBit0(&enc->rc, &enc->states.is_rep0_long[enc->states.state][pos_state]);
enc->states.state = SHORT_REP_NEXT_STATE(enc->states.state);
}
FORCE_NOINLINE
static void LZMA_encodeRepMatchLong(LZMA2_ECtx *const enc, unsigned const len, unsigned const rep, size_t const pos_state)
{
DEBUGLOG(7, "LZMA_encodeRepMatchLong : length %u, rep %u", len, rep);
RC_encodeBit1(&enc->rc, &enc->states.is_match[enc->states.state][pos_state]);
RC_encodeBit1(&enc->rc, &enc->states.is_rep[enc->states.state]);
if (rep == 0) {
RC_encodeBit0(&enc->rc, &enc->states.is_rep_G0[enc->states.state]);
RC_encodeBit1(&enc->rc, &enc->states.is_rep0_long[enc->states.state][pos_state]);
}
else {
U32 const distance = enc->states.reps[rep];
RC_encodeBit1(&enc->rc, &enc->states.is_rep_G0[enc->states.state]);
if (rep == 1) {
RC_encodeBit0(&enc->rc, &enc->states.is_rep_G1[enc->states.state]);
}
else {
RC_encodeBit1(&enc->rc, &enc->states.is_rep_G1[enc->states.state]);
RC_encodeBit(&enc->rc, &enc->states.is_rep_G2[enc->states.state], rep - 2);
if (rep == 3)
enc->states.reps[3] = enc->states.reps[2];
enc->states.reps[2] = enc->states.reps[1];
}
enc->states.reps[1] = enc->states.reps[0];
enc->states.reps[0] = distance;
}
LZMA_encodeLength(enc, &enc->states.rep_len_states, len, pos_state);
enc->states.state = REP_NEXT_STATE(enc->states.state);
++enc->rep_len_price_count;
}
/*
* Distance slot functions based on fastpos.h from XZ
*/
HINT_INLINE
unsigned LZMA_fastDistShift(unsigned const n)
{
return n * (kFastDistBits - 1);
}
HINT_INLINE
unsigned LZMA_fastDistResult(U32 const dist, unsigned const n)
{
return distance_table[dist >> LZMA_fastDistShift(n)]
+ 2 * LZMA_fastDistShift(n);
}
static size_t LZMA_getDistSlot(U32 const distance)
{
U32 limit = 1UL << kFastDistBits;
/* If it is small enough, we can pick the result directly from */
/* the precalculated table. */
if (distance < limit) {
return distance_table[distance];
}
limit <<= LZMA_fastDistShift(1);
if (distance < limit) {
return LZMA_fastDistResult(distance, 1);
}
return LZMA_fastDistResult(distance, 2);
}
/* * */
HINT_INLINE
void LZMA_encodeNormalMatch(LZMA2_ECtx *const enc, unsigned const len, U32 const dist, size_t const pos_state)
{
DEBUGLOG(7, "LZMA_encodeNormalMatch : length %u, dist %u", len, dist);
RC_encodeBit1(&enc->rc, &enc->states.is_match[enc->states.state][pos_state]);
RC_encodeBit0(&enc->rc, &enc->states.is_rep[enc->states.state]);
enc->states.state = MATCH_NEXT_STATE(enc->states.state);
LZMA_encodeLength(enc, &enc->states.len_states, len, pos_state);
size_t const dist_slot = LZMA_getDistSlot(dist);
RC_encodeBitTree(&enc->rc, enc->states.dist_slot_encoders[LEN_TO_DIST_STATE(len)], kNumPosSlotBits, (unsigned)dist_slot);
if (dist_slot >= kStartPosModelIndex) {
unsigned const footer_bits = ((unsigned)(dist_slot >> 1) - 1);
size_t const base = ((2 | (dist_slot & 1)) << footer_bits);
unsigned const dist_reduced = (unsigned)(dist - base);
if (dist_slot < kEndPosModelIndex) {
RC_encodeBitTreeReverse(&enc->rc, enc->states.dist_encoders + base - dist_slot - 1, footer_bits, dist_reduced);
}
else {
RC_encodeDirect(&enc->rc, dist_reduced >> kNumAlignBits, footer_bits - kNumAlignBits);
RC_encodeBitTreeReverse(&enc->rc, enc->states.dist_align_encoders, kNumAlignBits, dist_reduced & kAlignMask);
}
}
enc->states.reps[3] = enc->states.reps[2];
enc->states.reps[2] = enc->states.reps[1];
enc->states.reps[1] = enc->states.reps[0];
enc->states.reps[0] = dist;
++enc->match_price_count;
}
FORCE_INLINE_TEMPLATE
size_t LZMA_encodeChunkFast(LZMA2_ECtx *const enc,
FL2_dataBlock const block,
FL2_matchTable* const tbl,
int const struct_tbl,
size_t pos,
size_t const uncompressed_end)
{
size_t const pos_mask = enc->pos_mask;
size_t prev = pos;
unsigned const search_depth = tbl->params.depth;
while (pos < uncompressed_end && enc->rc.out_index < enc->chunk_size) {
size_t max_len;
const BYTE* data;
/* Table of distance restrictions for short matches */
static const U32 max_dist_table[] = { 0, 0, 0, 1 << 6, 1 << 14 };
/* Get a match from the table, extended to its full length */
RMF_match best_match = RMF_getMatch(block, tbl, search_depth, struct_tbl, pos);
if (best_match.length < kMatchLenMin) {
++pos;
continue;
}
/* Use if near enough */
if (best_match.length >= 5 || best_match.dist < max_dist_table[best_match.length])
best_match.dist += kNumReps;
else
best_match.length = 0;
max_len = MIN(kMatchLenMax, block.end - pos);
data = block.data + pos;
RMF_match best_rep = { 0, 0 };
RMF_match rep_match;
/* Search all of the rep distances */
for (rep_match.dist = 0; rep_match.dist < kNumReps; ++rep_match.dist) {
const BYTE *data_2 = data - enc->states.reps[rep_match.dist] - 1;
if (MEM_read16(data) != MEM_read16(data_2))
continue;
rep_match.length = (U32)(ZSTD_count(data + 2, data_2 + 2, data + max_len) + 2);
if (rep_match.length >= max_len) {
best_match = rep_match;
goto _encode;
}
if (rep_match.length > best_rep.length)
best_rep = rep_match;
}
/* Encode if it is kMatchLenMax or completes the block */
if (best_match.length >= max_len)
goto _encode;
if (best_rep.length >= 2) {
if (best_rep.length > best_match.length) {
best_match = best_rep;
}
else {
/* Modified ZSTD scheme for estimating cost */
int const gain2 = (int)(best_rep.length * 3 - best_rep.dist);
int const gain1 = (int)(best_match.length * 3 - ZSTD_highbit32(best_match.dist + 1) + 1);
if (gain2 > gain1) {
DEBUGLOG(7, "Replace match (%u, %u) with rep (%u, %u)", best_match.length, best_match.dist, best_rep.length, best_rep.dist);
best_match = best_rep;
}
}
}
if (best_match.length < kMatchLenMin) {
++pos;
continue;
}
for (size_t next = pos + 1; best_match.length < kMatchLenMax && next < uncompressed_end; ++next) {
/* lazy matching scheme from ZSTD */
RMF_match next_match = RMF_getNextMatch(block, tbl, search_depth, struct_tbl, next);
if (next_match.length >= kMatchLenMin) {
best_rep.length = 0;
data = block.data + next;
max_len = MIN(kMatchLenMax, block.end - next);
for (rep_match.dist = 0; rep_match.dist < kNumReps; ++rep_match.dist) {
const BYTE *data_2 = data - enc->states.reps[rep_match.dist] - 1;
if (MEM_read16(data) != MEM_read16(data_2))
continue;
rep_match.length = (U32)(ZSTD_count(data + 2, data_2 + 2, data + max_len) + 2);
if (rep_match.length > best_rep.length)
best_rep = rep_match;
}
if (best_rep.length >= 3) {
int const gain2 = (int)(best_rep.length * 3 - best_rep.dist);
int const gain1 = (int)(best_match.length * 3 - ZSTD_highbit32((U32)best_match.dist + 1) + 1);
if (gain2 > gain1) {
DEBUGLOG(7, "Replace match (%u, %u) with rep (%u, %u)", best_match.length, best_match.dist, best_rep.length, best_rep.dist);
best_match = best_rep;
pos = next;
}
}
if (next_match.length >= 3 && next_match.dist != best_match.dist) {
int const gain2 = (int)(next_match.length * 4 - ZSTD_highbit32((U32)next_match.dist + 1)); /* raw approx */
int const gain1 = (int)(best_match.length * 4 - ZSTD_highbit32((U32)best_match.dist + 1) + 4);
if (gain2 > gain1) {
DEBUGLOG(7, "Replace match (%u, %u) with match (%u, %u)", best_match.length, best_match.dist, next_match.length, next_match.dist + kNumReps);
best_match = next_match;
best_match.dist += kNumReps;
pos = next;
continue;
}
}
}
++next;
/* Recheck next < uncompressed_end. uncompressed_end could be block.end so decrementing the max chunk size won't obviate the need. */
if (next >= uncompressed_end)
break;
next_match = RMF_getNextMatch(block, tbl, search_depth, struct_tbl, next);
if (next_match.length < 4)
break;
data = block.data + next;
max_len = MIN(kMatchLenMax, block.end - next);
best_rep.length = 0;
for (rep_match.dist = 0; rep_match.dist < kNumReps; ++rep_match.dist) {
const BYTE *data_2 = data - enc->states.reps[rep_match.dist] - 1;
if (MEM_read16(data) != MEM_read16(data_2))
continue;
rep_match.length = (U32)(ZSTD_count(data + 2, data_2 + 2, data + max_len) + 2);
if (rep_match.length > best_rep.length)
best_rep = rep_match;
}
if (best_rep.length >= 4) {
int const gain2 = (int)(best_rep.length * 4 - (best_rep.dist >> 1));
int const gain1 = (int)(best_match.length * 4 - ZSTD_highbit32((U32)best_match.dist + 1) + 1);
if (gain2 > gain1) {
DEBUGLOG(7, "Replace match (%u, %u) with rep (%u, %u)", best_match.length, best_match.dist, best_rep.length, best_rep.dist);
best_match = best_rep;
pos = next;
}
}
if (next_match.dist != best_match.dist) {
int const gain2 = (int)(next_match.length * 4 - ZSTD_highbit32((U32)next_match.dist + 1));
int const gain1 = (int)(best_match.length * 4 - ZSTD_highbit32((U32)best_match.dist + 1) + 7);
if (gain2 > gain1) {
DEBUGLOG(7, "Replace match (%u, %u) with match (%u, %u)", best_match.length, best_match.dist, next_match.length, next_match.dist + kNumReps);
best_match = next_match;
best_match.dist += kNumReps;
pos = next;
continue;
}
}
break;
}
_encode:
assert(pos + best_match.length <= block.end);
while (prev < pos) {
if (enc->rc.out_index >= enc->chunk_limit)
return prev;
if (block.data[prev] != block.data[prev - enc->states.reps[0] - 1]) {
LZMA_encodeLiteralBuf(enc, block.data, prev);
++prev;
}
else {
LZMA_encodeRepMatchShort(enc, prev & pos_mask);
++prev;
}
}
if(best_match.length >= kMatchLenMin) {
if (best_match.dist >= kNumReps) {
LZMA_encodeNormalMatch(enc, best_match.length, best_match.dist - kNumReps, pos & pos_mask);
pos += best_match.length;
prev = pos;
}
else {
LZMA_encodeRepMatchLong(enc, best_match.length, best_match.dist, pos & pos_mask);
pos += best_match.length;
prev = pos;
}
}
}
while (prev < pos && enc->rc.out_index < enc->chunk_limit) {
if (block.data[prev] != block.data[prev - enc->states.reps[0] - 1])
LZMA_encodeLiteralBuf(enc, block.data, prev);
else
LZMA_encodeRepMatchShort(enc, prev & pos_mask);
++prev;
}
return prev;
}
/*
* Reverse the direction of the linked list generated by the optimal parser
*/
FORCE_NOINLINE
static void LZMA_reverseOptimalChain(LZMA2_node* const opt_buf, size_t cur)
{
unsigned len = (unsigned)opt_buf[cur].len;
U32 dist = opt_buf[cur].dist;
for(;;) {
unsigned const extra = (unsigned)opt_buf[cur].extra;
cur -= len;
if (extra) {
opt_buf[cur].len = (U32)len;
len = extra;
if (extra == 1) {
opt_buf[cur].dist = dist;
dist = kNullDist;
--cur;
}
else {
opt_buf[cur].dist = 0;
--cur;
--len;
opt_buf[cur].dist = kNullDist;
opt_buf[cur].len = 1;
cur -= len;
}
}
unsigned const next_len = opt_buf[cur].len;
U32 const next_dist = opt_buf[cur].dist;
opt_buf[cur].dist = dist;
opt_buf[cur].len = (U32)len;
if (cur == 0)
break;
len = next_len;
dist = next_dist;
}
}
static unsigned LZMA_getLiteralPrice(LZMA2_ECtx *const enc, size_t const pos, size_t const state, unsigned const prev_symbol, U32 symbol, unsigned const match_byte)
{
const LZMA2_prob* const prob_table = LITERAL_PROBS(enc, pos, prev_symbol);
if (IS_LIT_STATE(state)) {
unsigned price = 0;
symbol |= 0x100;
do {
price += GET_PRICE(prob_table[symbol >> 8], (symbol >> 7) & 1);
symbol <<= 1;
} while (symbol < 0x10000);
return price;
}
return LZMA_getLiteralPriceMatched(prob_table, symbol, match_byte);
}
/*
* Reset the hash object for encoding a new slice of a block
*/
static void LZMA_hashReset(LZMA2_ECtx *const enc, unsigned const dictionary_bits_3)
{
enc->hash_dict_3 = (ptrdiff_t)1 << dictionary_bits_3;
enc->chain_mask_3 = enc->hash_dict_3 - 1;
memset(enc->hash_buf->table_3, 0xFF, sizeof(enc->hash_buf->table_3));
}
/*
* Create hash table and chain with dict size dictionary_bits_3. Frees any existing object.
*/
static int LZMA_hashCreate(LZMA2_ECtx *const enc, unsigned const dictionary_bits_3)
{
DEBUGLOG(3, "Create hash chain : dict bits %u", dictionary_bits_3);
if (enc->hash_buf)
free(enc->hash_buf);
enc->hash_alloc_3 = (ptrdiff_t)1 << dictionary_bits_3;
enc->hash_buf = malloc(sizeof(LZMA2_hc3) + (enc->hash_alloc_3 - 1) * sizeof(S32));
if (enc->hash_buf == NULL)
return 1;
LZMA_hashReset(enc, dictionary_bits_3);
return 0;
}
/* Create a hash chain for hybrid mode if options require one.
* Used for allocating before compression begins. Any existing table will be reused if
* it is at least as large as required.
*/
int LZMA2_hashAlloc(LZMA2_ECtx *const enc, const FL2_lzma2Parameters* const options)
{
if (enc->strategy == FL2_ultra && enc->hash_alloc_3 < ((ptrdiff_t)1 << options->second_dict_bits))
return LZMA_hashCreate(enc, options->second_dict_bits);
return 0;
}
#define GET_HASH_3(data) ((((MEM_readLE32(data)) << 8) * 506832829U) >> (32 - kHash3Bits))
/* Find matches nearer than the match from the RMF. If none is at least as long as
* the RMF match (most likely), insert that match at the end of the list.
*/
HINT_INLINE
size_t LZMA_hashGetMatches(LZMA2_ECtx *const enc, FL2_dataBlock const block,
ptrdiff_t const pos,
size_t const length_limit,
RMF_match const match)
{
ptrdiff_t const hash_dict_3 = enc->hash_dict_3;
const BYTE* data = block.data;
LZMA2_hc3* const tbl = enc->hash_buf;
ptrdiff_t const chain_mask_3 = enc->chain_mask_3;
enc->match_count = 0;
enc->hash_prev_index = MAX(enc->hash_prev_index, pos - hash_dict_3);
/* Update hash tables and chains for any positions that were skipped */
while (++enc->hash_prev_index < pos) {
size_t hash = GET_HASH_3(data + enc->hash_prev_index);
tbl->hash_chain_3[enc->hash_prev_index & chain_mask_3] = tbl->table_3[hash];
tbl->table_3[hash] = (S32)enc->hash_prev_index;
}
data += pos;
size_t const hash = GET_HASH_3(data);
ptrdiff_t const first_3 = tbl->table_3[hash];
tbl->table_3[hash] = (S32)pos;
size_t max_len = 2;
if (first_3 >= 0) {
int cycles = enc->match_cycles;
ptrdiff_t const end_index = pos - (((ptrdiff_t)match.dist < hash_dict_3) ? match.dist : hash_dict_3);
ptrdiff_t match_3 = first_3;
if (match_3 >= end_index) {
do {
--cycles;
const BYTE* data_2 = block.data + match_3;
size_t len_test = ZSTD_count(data + 1, data_2 + 1, data + length_limit) + 1;
if (len_test > max_len) {
enc->matches[enc->match_count].length = (U32)len_test;
enc->matches[enc->match_count].dist = (U32)(pos - match_3 - 1);
++enc->match_count;
max_len = len_test;
if (len_test >= length_limit)
break;
}
if (cycles <= 0)
break;
match_3 = tbl->hash_chain_3[match_3 & chain_mask_3];
} while (match_3 >= end_index);
}
}
tbl->hash_chain_3[pos & chain_mask_3] = (S32)first_3;
if ((unsigned)max_len < match.length) {
/* Insert the match from the RMF */
enc->matches[enc->match_count] = match;
++enc->match_count;
return match.length;
}
return max_len;
}
/* The speed of this function is critical. The sections have many variables
* in common, so breaking it up into shorter functions is not feasible.
* For each position cur, starting at 1, check some or all possible
* encoding choices - a literal, 1-byte rep 0 match, all rep match lengths, and
* all match lengths at available distances. It also checks the combined
* sequences literal+rep0, rep+lit+rep0 and match+lit+rep0.
* If is_hybrid != 0, this method works in hybrid mode, using the
* hash chain to find shorter matches at near distances. */
FORCE_INLINE_TEMPLATE
size_t LZMA_optimalParse(LZMA2_ECtx* const enc, FL2_dataBlock const block,
RMF_match match,
size_t const pos,
size_t const cur,
size_t len_end,
int const is_hybrid,
U32* const reps)
{
LZMA2_node* const cur_opt = &enc->opt_buf[cur];
size_t const pos_mask = enc->pos_mask;
size_t const pos_state = (pos & pos_mask);
const BYTE* const data = block.data + pos;
size_t const fast_length = enc->fast_length;
size_t prev_index = cur - cur_opt->len;
size_t state;
size_t bytes_avail;
U32 match_price;
U32 rep_match_price;
/* Update the states according to how this location was reached */
if (cur_opt->len == 1) {
/* Literal or 1-byte rep */
const BYTE *next_state = (cur_opt->dist == 0) ? kShortRepNextStates : kLiteralNextStates;
state = next_state[enc->opt_buf[prev_index].state];
}
else {
/* Match or rep match */
size_t const dist = cur_opt->dist;
if (cur_opt->extra) {
prev_index -= cur_opt->extra;
state = kState_RepAfterLit - ((dist >= kNumReps) & (cur_opt->extra == 1));
}
else {
state = enc->opt_buf[prev_index].state;
state = MATCH_NEXT_STATE(state) + (dist < kNumReps);
}
const LZMA2_node *const prev_opt = &enc->opt_buf[prev_index];
if (dist < kNumReps) {
/* Move the chosen rep to the front.
* The table is hideous but faster than branching :D */
reps[0] = prev_opt->reps[dist];
size_t table = 1 | (2 << 2) | (3 << 4)
| (0 << 8) | (2 << 10) | (3 << 12)
| (0L << 16) | (1L << 18) | (3L << 20)
| (0L << 24) | (1L << 26) | (2L << 28);
table >>= (dist << 3);
reps[1] = prev_opt->reps[table & 3];
table >>= 2;
reps[2] = prev_opt->reps[table & 3];
table >>= 2;
reps[3] = prev_opt->reps[table & 3];