-
Notifications
You must be signed in to change notification settings - Fork 21
/
lzms_compress.c
2228 lines (1887 loc) · 70 KB
/
lzms_compress.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
/*
* lzms_compress.c
*
* A compressor for the LZMS compression format.
*/
/*
* Copyright (C) 2013, 2014, 2015 Eric Biggers
*
* This file is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option) any
* later version.
*
* This file is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this file; if not, see https://www.gnu.org/licenses/.
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include <limits.h>
#include <string.h>
#include "wimlib/compress_common.h"
#include "wimlib/compressor_ops.h"
#include "wimlib/error.h"
#include "wimlib/lcpit_matchfinder.h"
#include "wimlib/lzms_common.h"
#include "wimlib/matchfinder_common.h"
#include "wimlib/unaligned.h"
#include "wimlib/util.h"
/*
* MAX_FAST_LENGTH is the maximum match length for which the length slot can be
* looked up directly in 'fast_length_slot_tab' and the length cost can be
* looked up directly in 'fast_length_cost_tab'.
*
* We also limit the 'nice_match_len' parameter to this value. Consequently, if
* the longest match found is shorter than 'nice_match_len', then it must also
* be shorter than MAX_FAST_LENGTH. This makes it possible to do fast lookups
* of length costs using 'fast_length_cost_tab' without having to keep checking
* whether the length exceeds MAX_FAST_LENGTH or not.
*/
#define MAX_FAST_LENGTH 255
/* NUM_OPTIM_NODES is the maximum number of bytes the parsing algorithm will
* step forward before forcing the pending items to be encoded. If this value
* is increased, then there will be fewer forced flushes, but the probability
* entries and Huffman codes will be more likely to become outdated. */
#define NUM_OPTIM_NODES 2048
/* COST_SHIFT is a scaling factor that makes it possible to consider fractional
* bit costs. A single bit has a cost of (1 << COST_SHIFT). */
#define COST_SHIFT 6
/* Length of the hash table for finding delta matches */
#define DELTA_HASH_ORDER 17
#define DELTA_HASH_LENGTH ((u32)1 << DELTA_HASH_ORDER)
/* The number of bytes to hash when finding delta matches; also taken to be the
* minimum length of an explicit offset delta match */
#define NBYTES_HASHED_FOR_DELTA 3
/* The number of delta match powers to consider (must be <=
* LZMS_NUM_DELTA_POWER_SYMS) */
#define NUM_POWERS_TO_CONSIDER 6
/* This structure tracks the state of writing bits as a series of 16-bit coding
* units, starting at the end of the output buffer and proceeding backwards. */
struct lzms_output_bitstream {
/* Bits that haven't yet been written to the output buffer */
u64 bitbuf;
/* Number of bits currently held in @bitbuf */
unsigned bitcount;
/* Pointer to the beginning of the output buffer (this is the "end" when
* writing backwards!) */
u8 *begin;
/* Pointer to just past the next position in the output buffer at which
* to output a 16-bit coding unit */
u8 *next;
};
/* This structure tracks the state of range encoding and its output, which
* starts at the beginning of the output buffer and proceeds forwards. */
struct lzms_range_encoder {
/* The lower boundary of the current range. Logically, this is a 33-bit
* integer whose high bit is needed to detect carries. */
u64 lower_bound;
/* The size of the current range */
u32 range_size;
/* The next 16-bit coding unit to output */
u16 cache;
/* The number of 16-bit coding units whose output has been delayed due
* to possible carrying. The first such coding unit is @cache; all
* subsequent such coding units are 0xffff. */
u32 cache_size;
/* Pointer to the beginning of the output buffer */
u8 *begin;
/* Pointer to the position in the output buffer at which the next coding
* unit must be written */
u8 *next;
/* Pointer to just past the end of the output buffer */
u8 *end;
};
/* Bookkeeping information for an adaptive Huffman code */
struct lzms_huffman_rebuild_info {
/* The remaining number of symbols to encode until this code must be
* rebuilt */
unsigned num_syms_until_rebuild;
/* The number of symbols in this code */
unsigned num_syms;
/* The rebuild frequency of this code, in symbols */
unsigned rebuild_freq;
/* The Huffman codeword of each symbol in this code */
u32 *codewords;
/* The length of each Huffman codeword, in bits */
u8 *lens;
/* The frequency of each symbol in this code */
u32 *freqs;
};
/*
* The compressor-internal representation of a match or literal.
*
* Literals have length=1; matches have length > 1. (We disallow matches of
* length 1, even though this is a valid length in LZMS.)
*
* The source is encoded as follows:
*
* - Literals: the literal byte itself
* - Explicit offset LZ matches: the match offset plus (LZMS_NUM_LZ_REPS - 1)
* - Repeat offset LZ matches: the index of the offset in recent_lz_offsets
* - Explicit offset delta matches: DELTA_SOURCE_TAG is set, the next 3 bits are
* the power, and the remainder is the raw offset plus (LZMS_NUM_DELTA_REPS-1)
* - Repeat offset delta matches: DELTA_SOURCE_TAG is set, and the remainder is
* the index of the (power, raw_offset) pair in recent_delta_pairs
*/
struct lzms_item {
u32 length;
u32 source;
};
#define DELTA_SOURCE_TAG ((u32)1 << 31)
#define DELTA_SOURCE_POWER_SHIFT 28
#define DELTA_SOURCE_RAW_OFFSET_MASK (((u32)1 << DELTA_SOURCE_POWER_SHIFT) - 1)
static void __attribute__((unused))
check_that_powers_fit_in_bitfield(void)
{
STATIC_ASSERT(LZMS_NUM_DELTA_POWER_SYMS <= (1 << (31 - DELTA_SOURCE_POWER_SHIFT)));
}
/* A stripped-down version of the adaptive state in LZMS which excludes the
* probability entries and Huffman codes */
struct lzms_adaptive_state {
/* Recent offsets for LZ matches */
u32 recent_lz_offsets[LZMS_NUM_LZ_REPS + 1];
u32 prev_lz_offset; /* 0 means none */
u32 upcoming_lz_offset; /* 0 means none */
/* Recent (power, raw offset) pairs for delta matches.
* The low DELTA_SOURCE_POWER_SHIFT bits of each entry are the raw
* offset, and the high bits are the power. */
u32 recent_delta_pairs[LZMS_NUM_DELTA_REPS + 1];
u32 prev_delta_pair; /* 0 means none */
u32 upcoming_delta_pair; /* 0 means none */
/* States for predicting the probabilities of item types */
u8 main_state;
u8 match_state;
u8 lz_state;
u8 lz_rep_states[LZMS_NUM_LZ_REP_DECISIONS];
u8 delta_state;
u8 delta_rep_states[LZMS_NUM_DELTA_REP_DECISIONS];
} __attribute__((aligned(64)));
/*
* This structure represents a byte position in the preprocessed input data and
* a node in the graph of possible match/literal choices.
*
* Logically, each incoming edge to this node is labeled with a literal or a
* match that can be taken to reach this position from an earlier position; and
* each outgoing edge from this node is labeled with a literal or a match that
* can be taken to advance from this position to a later position.
*/
struct lzms_optimum_node {
/*
* The cost of the lowest-cost path that has been found to reach this
* position. This can change as progressively lower cost paths are
* found to reach this position.
*/
u32 cost;
#define INFINITE_COST UINT32_MAX
/*
* @item is the last item that was taken to reach this position to reach
* it with the stored @cost. This can change as progressively lower
* cost paths are found to reach this position.
*
* In some cases we look ahead more than one item. If we looked ahead n
* items to reach this position, then @item is the last item taken,
* @extra_items contains the other items ordered from second-to-last to
* first, and @num_extra_items is n - 1.
*/
unsigned num_extra_items;
struct lzms_item item;
struct lzms_item extra_items[2];
/*
* The adaptive state that exists at this position. This is filled in
* lazily, only after the minimum-cost path to this position is found.
*
* Note: the way the algorithm handles this adaptive state in the
* "minimum-cost" parse is actually only an approximation. It's
* possible for the globally optimal, minimum cost path to contain a
* prefix, ending at a position, where that path prefix is *not* the
* minimum cost path to that position. This can happen if such a path
* prefix results in a different adaptive state which results in lower
* costs later. Although the algorithm does do some heuristic
* multi-item lookaheads, it does not solve this problem in general.
*
* Note: this adaptive state structure also does not include the
* probability entries or current Huffman codewords. Those aren't
* maintained per-position and are only updated occasionally.
*/
struct lzms_adaptive_state state;
} __attribute__((aligned(64)));
/* The main compressor structure */
struct lzms_compressor {
/* The matchfinder for LZ matches */
struct lcpit_matchfinder mf;
/* The preprocessed buffer of data being compressed */
u8 *in_buffer;
/* The number of bytes of data to be compressed, which is the number of
* bytes of data in @in_buffer that are actually valid */
size_t in_nbytes;
/*
* Boolean flags to enable consideration of various types of multi-step
* operations during parsing.
*
* Among other cases, multi-step operations can help with gaps where two
* matches are separated by a non-matching byte.
*
* This idea is borrowed from Igor Pavlov's LZMA encoder.
*/
bool try_lit_lzrep0;
bool try_lzrep_lit_lzrep0;
bool try_lzmatch_lit_lzrep0;
/*
* If true, the compressor can use delta matches. This slows down
* compression. It improves the compression ratio greatly, slightly, or
* not at all, depending on the input data.
*/
bool use_delta_matches;
/* If true, the compressor need not preserve the input buffer if it
* compresses the data successfully. */
bool destructive;
/* 'last_target_usages' is a large array that is only needed for
* preprocessing, so it is in union with fields that don't need to be
* initialized until after preprocessing. */
union {
struct {
/* Temporary space to store matches found by the LZ matchfinder */
struct lz_match matches[MAX_FAST_LENGTH - LZMS_MIN_MATCH_LENGTH + 1];
/* Hash table for finding delta matches */
u32 delta_hash_table[DELTA_HASH_LENGTH];
/* For each delta power, the hash code for the next sequence */
u32 next_delta_hashes[NUM_POWERS_TO_CONSIDER];
/* The per-byte graph nodes for near-optimal parsing */
struct lzms_optimum_node optimum_nodes[NUM_OPTIM_NODES + MAX_FAST_LENGTH +
1 + MAX_FAST_LENGTH];
/* Table: length => current cost for small match lengths */
u32 fast_length_cost_tab[MAX_FAST_LENGTH + 1];
/* Range encoder which outputs to the beginning of the compressed data
* buffer, proceeding forwards */
struct lzms_range_encoder rc;
/* Bitstream which outputs to the end of the compressed data buffer,
* proceeding backwards */
struct lzms_output_bitstream os;
/* States and probability entries for item type disambiguation */
unsigned main_state;
unsigned match_state;
unsigned lz_state;
unsigned lz_rep_states[LZMS_NUM_LZ_REP_DECISIONS];
unsigned delta_state;
unsigned delta_rep_states[LZMS_NUM_DELTA_REP_DECISIONS];
struct lzms_probabilites probs;
/* Huffman codes */
struct lzms_huffman_rebuild_info literal_rebuild_info;
u32 literal_codewords[LZMS_NUM_LITERAL_SYMS];
u8 literal_lens[LZMS_NUM_LITERAL_SYMS];
u32 literal_freqs[LZMS_NUM_LITERAL_SYMS];
struct lzms_huffman_rebuild_info lz_offset_rebuild_info;
u32 lz_offset_codewords[LZMS_MAX_NUM_OFFSET_SYMS];
u8 lz_offset_lens[LZMS_MAX_NUM_OFFSET_SYMS];
u32 lz_offset_freqs[LZMS_MAX_NUM_OFFSET_SYMS];
struct lzms_huffman_rebuild_info length_rebuild_info;
u32 length_codewords[LZMS_NUM_LENGTH_SYMS];
u8 length_lens[LZMS_NUM_LENGTH_SYMS];
u32 length_freqs[LZMS_NUM_LENGTH_SYMS];
struct lzms_huffman_rebuild_info delta_offset_rebuild_info;
u32 delta_offset_codewords[LZMS_MAX_NUM_OFFSET_SYMS];
u8 delta_offset_lens[LZMS_MAX_NUM_OFFSET_SYMS];
u32 delta_offset_freqs[LZMS_MAX_NUM_OFFSET_SYMS];
struct lzms_huffman_rebuild_info delta_power_rebuild_info;
u32 delta_power_codewords[LZMS_NUM_DELTA_POWER_SYMS];
u8 delta_power_lens[LZMS_NUM_DELTA_POWER_SYMS];
u32 delta_power_freqs[LZMS_NUM_DELTA_POWER_SYMS];
}; /* struct */
s32 last_target_usages[65536];
}; /* union */
/* Table: length => length slot for small match lengths */
u8 fast_length_slot_tab[MAX_FAST_LENGTH + 1];
/* Tables for mapping offsets to offset slots */
/* slots [0, 167); 0 <= num_extra_bits <= 10 */
u8 offset_slot_tab_1[0xe4a5];
/* slots [167, 427); 11 <= num_extra_bits <= 15 */
u16 offset_slot_tab_2[0x3d0000 >> 11];
/* slots [427, 799); 16 <= num_extra_bits */
u16 offset_slot_tab_3[((LZMS_MAX_MATCH_OFFSET + 1) - 0xe4a5) >> 16];
};
/******************************************************************************
* Offset and length slot acceleration *
******************************************************************************/
/* Generate the acceleration table for length slots. */
static void
lzms_init_fast_length_slot_tab(struct lzms_compressor *c)
{
unsigned slot = 0;
for (u32 len = LZMS_MIN_MATCH_LENGTH; len <= MAX_FAST_LENGTH; len++) {
if (len >= lzms_length_slot_base[slot + 1])
slot++;
c->fast_length_slot_tab[len] = slot;
}
}
/* Generate the acceleration tables for offset slots. */
static void
lzms_init_offset_slot_tabs(struct lzms_compressor *c)
{
u32 offset;
unsigned slot = 0;
/* slots [0, 167); 0 <= num_extra_bits <= 10 */
for (offset = 1; offset < 0xe4a5; offset++) {
if (offset >= lzms_offset_slot_base[slot + 1])
slot++;
c->offset_slot_tab_1[offset] = slot;
}
/* slots [167, 427); 11 <= num_extra_bits <= 15 */
for (; offset < 0x3de4a5; offset += (u32)1 << 11) {
if (offset >= lzms_offset_slot_base[slot + 1])
slot++;
c->offset_slot_tab_2[(offset - 0xe4a5) >> 11] = slot;
}
/* slots [427, 799); 16 <= num_extra_bits */
for (; offset < LZMS_MAX_MATCH_OFFSET + 1; offset += (u32)1 << 16) {
if (offset >= lzms_offset_slot_base[slot + 1])
slot++;
c->offset_slot_tab_3[(offset - 0xe4a5) >> 16] = slot;
}
}
/*
* Return the length slot for the specified match length, using the compressor's
* acceleration table if the length is small enough.
*/
static forceinline unsigned
lzms_comp_get_length_slot(const struct lzms_compressor *c, u32 length)
{
if (likely(length <= MAX_FAST_LENGTH))
return c->fast_length_slot_tab[length];
return lzms_get_length_slot(length);
}
/*
* Return the offset slot for the specified match offset, using the compressor's
* acceleration tables to speed up the mapping.
*/
static forceinline unsigned
lzms_comp_get_offset_slot(const struct lzms_compressor *c, u32 offset)
{
if (offset < 0xe4a5)
return c->offset_slot_tab_1[offset];
offset -= 0xe4a5;
if (offset < 0x3d0000)
return c->offset_slot_tab_2[offset >> 11];
return c->offset_slot_tab_3[offset >> 16];
}
/******************************************************************************
* Range encoding *
******************************************************************************/
/*
* Initialize the range encoder @rc to write forwards to the specified buffer
* @out that is @size bytes long.
*/
static void
lzms_range_encoder_init(struct lzms_range_encoder *rc, u8 *out, size_t size)
{
rc->lower_bound = 0;
rc->range_size = 0xffffffff;
rc->cache = 0;
rc->cache_size = 1;
rc->begin = out;
rc->next = out - sizeof(le16);
rc->end = out + (size & ~1);
}
/*
* Attempt to flush bits from the range encoder.
*
* The basic idea is that we're writing bits from @rc->lower_bound to the
* output. However, due to carrying, the writing of coding units with the
* maximum value, as well as one prior coding unit, must be delayed until it is
* determined whether a carry is needed.
*
* This is based on the public domain code for LZMA written by Igor Pavlov, but
* with the following differences:
*
* - In LZMS, 16-bit coding units are required rather than 8-bit.
*
* - In LZMS, the first coding unit is not ignored by the decompressor, so
* the encoder cannot output a dummy value to that position.
*/
static void
lzms_range_encoder_shift_low(struct lzms_range_encoder *rc)
{
if ((u32)(rc->lower_bound) < 0xffff0000 ||
(u32)(rc->lower_bound >> 32) != 0)
{
/* Carry not needed (rc->lower_bound < 0xffff0000), or carry
* occurred ((rc->lower_bound >> 32) != 0, a.k.a. the carry bit
* is 1). */
do {
if (likely(rc->next >= rc->begin)) {
if (rc->next != rc->end) {
put_unaligned_le16(rc->cache +
(u16)(rc->lower_bound >> 32),
rc->next);
rc->next += sizeof(le16);
}
} else {
rc->next += sizeof(le16);
}
rc->cache = 0xffff;
} while (--rc->cache_size != 0);
rc->cache = (rc->lower_bound >> 16) & 0xffff;
}
++rc->cache_size;
rc->lower_bound = (rc->lower_bound & 0xffff) << 16;
}
static bool
lzms_range_encoder_flush(struct lzms_range_encoder *rc)
{
for (int i = 0; i < 4; i++)
lzms_range_encoder_shift_low(rc);
return rc->next != rc->end;
}
/*
* Encode the next bit using the range encoder.
*
* @prob is the probability out of LZMS_PROBABILITY_DENOMINATOR that the next
* bit is 0 rather than 1.
*/
static forceinline void
lzms_range_encode_bit(struct lzms_range_encoder *rc, int bit, u32 prob)
{
/* Normalize if needed. */
if (rc->range_size <= 0xffff) {
rc->range_size <<= 16;
lzms_range_encoder_shift_low(rc);
}
u32 bound = (rc->range_size >> LZMS_PROBABILITY_BITS) * prob;
if (bit == 0) {
rc->range_size = bound;
} else {
rc->lower_bound += bound;
rc->range_size -= bound;
}
}
/*
* Encode a bit. This wraps around lzms_range_encode_bit() to handle using and
* updating the state and its corresponding probability entry.
*/
static forceinline void
lzms_encode_bit(int bit, unsigned *state_p, unsigned num_states,
struct lzms_probability_entry *probs,
struct lzms_range_encoder *rc)
{
struct lzms_probability_entry *prob_entry;
u32 prob;
/* Load the probability entry for the current state. */
prob_entry = &probs[*state_p];
/* Update the state based on the next bit. */
*state_p = ((*state_p << 1) | bit) & (num_states - 1);
/* Get the probability that the bit is 0. */
prob = lzms_get_probability(prob_entry);
/* Update the probability entry. */
lzms_update_probability_entry(prob_entry, bit);
/* Encode the bit using the range encoder. */
lzms_range_encode_bit(rc, bit, prob);
}
/* Helper functions for encoding bits in the various decision classes */
static void
lzms_encode_main_bit(struct lzms_compressor *c, int bit)
{
lzms_encode_bit(bit, &c->main_state, LZMS_NUM_MAIN_PROBS,
c->probs.main, &c->rc);
}
static void
lzms_encode_match_bit(struct lzms_compressor *c, int bit)
{
lzms_encode_bit(bit, &c->match_state, LZMS_NUM_MATCH_PROBS,
c->probs.match, &c->rc);
}
static void
lzms_encode_lz_bit(struct lzms_compressor *c, int bit)
{
lzms_encode_bit(bit, &c->lz_state, LZMS_NUM_LZ_PROBS,
c->probs.lz, &c->rc);
}
static void
lzms_encode_lz_rep_bit(struct lzms_compressor *c, int bit, int idx)
{
lzms_encode_bit(bit, &c->lz_rep_states[idx], LZMS_NUM_LZ_REP_PROBS,
c->probs.lz_rep[idx], &c->rc);
}
static void
lzms_encode_delta_bit(struct lzms_compressor *c, int bit)
{
lzms_encode_bit(bit, &c->delta_state, LZMS_NUM_DELTA_PROBS,
c->probs.delta, &c->rc);
}
static void
lzms_encode_delta_rep_bit(struct lzms_compressor *c, int bit, int idx)
{
lzms_encode_bit(bit, &c->delta_rep_states[idx], LZMS_NUM_DELTA_REP_PROBS,
c->probs.delta_rep[idx], &c->rc);
}
/******************************************************************************
* Huffman encoding and verbatim bits *
******************************************************************************/
/*
* Initialize the output bitstream @os to write backwards to the specified
* buffer @out that is @size bytes long.
*/
static void
lzms_output_bitstream_init(struct lzms_output_bitstream *os,
u8 *out, size_t size)
{
os->bitbuf = 0;
os->bitcount = 0;
os->begin = out;
os->next = out + (size & ~1);
}
/*
* Write some bits, contained in the low-order @num_bits bits of @bits, to the
* output bitstream @os.
*
* @max_num_bits is a compile-time constant that specifies the maximum number of
* bits that can ever be written at this call site.
*/
static forceinline void
lzms_write_bits(struct lzms_output_bitstream *os, const u32 bits,
const unsigned num_bits, const unsigned max_num_bits)
{
/* Add the bits to the bit buffer variable. */
os->bitcount += num_bits;
os->bitbuf = (os->bitbuf << num_bits) | bits;
/* Check whether any coding units need to be written. */
while (os->bitcount >= 16) {
os->bitcount -= 16;
/* Write a coding unit, unless it would underflow the buffer. */
if (os->next != os->begin) {
os->next -= sizeof(le16);
put_unaligned_le16(os->bitbuf >> os->bitcount, os->next);
}
/* Optimization for call sites that never write more than 16
* bits at once. */
if (max_num_bits <= 16)
break;
}
}
/*
* Flush the output bitstream, ensuring that all bits written to it have been
* written to memory. Return %true if all bits have been output successfully,
* or %false if an overrun occurred.
*/
static bool
lzms_output_bitstream_flush(struct lzms_output_bitstream *os)
{
if (os->next == os->begin)
return false;
if (os->bitcount != 0) {
os->next -= sizeof(le16);
put_unaligned_le16(os->bitbuf << (16 - os->bitcount), os->next);
}
return true;
}
static void
lzms_build_huffman_code(struct lzms_huffman_rebuild_info *rebuild_info)
{
make_canonical_huffman_code(rebuild_info->num_syms,
LZMS_MAX_CODEWORD_LENGTH,
rebuild_info->freqs,
rebuild_info->lens,
rebuild_info->codewords);
rebuild_info->num_syms_until_rebuild = rebuild_info->rebuild_freq;
}
static void
lzms_init_huffman_code(struct lzms_huffman_rebuild_info *rebuild_info,
unsigned num_syms, unsigned rebuild_freq,
u32 *codewords, u8 *lens, u32 *freqs)
{
rebuild_info->num_syms = num_syms;
rebuild_info->rebuild_freq = rebuild_freq;
rebuild_info->codewords = codewords;
rebuild_info->lens = lens;
rebuild_info->freqs = freqs;
lzms_init_symbol_frequencies(freqs, num_syms);
lzms_build_huffman_code(rebuild_info);
}
static void
lzms_rebuild_huffman_code(struct lzms_huffman_rebuild_info *rebuild_info)
{
lzms_build_huffman_code(rebuild_info);
lzms_dilute_symbol_frequencies(rebuild_info->freqs, rebuild_info->num_syms);
}
/*
* Encode a symbol using the specified Huffman code. Then, if the Huffman code
* needs to be rebuilt, rebuild it and return true; otherwise return false.
*/
static forceinline bool
lzms_huffman_encode_symbol(unsigned sym,
const u32 *codewords, const u8 *lens, u32 *freqs,
struct lzms_output_bitstream *os,
struct lzms_huffman_rebuild_info *rebuild_info)
{
lzms_write_bits(os, codewords[sym], lens[sym], LZMS_MAX_CODEWORD_LENGTH);
++freqs[sym];
if (--rebuild_info->num_syms_until_rebuild == 0) {
lzms_rebuild_huffman_code(rebuild_info);
return true;
}
return false;
}
/* Helper routines to encode symbols using the various Huffman codes */
static bool
lzms_encode_literal_symbol(struct lzms_compressor *c, unsigned sym)
{
return lzms_huffman_encode_symbol(sym, c->literal_codewords,
c->literal_lens, c->literal_freqs,
&c->os, &c->literal_rebuild_info);
}
static bool
lzms_encode_lz_offset_symbol(struct lzms_compressor *c, unsigned sym)
{
return lzms_huffman_encode_symbol(sym, c->lz_offset_codewords,
c->lz_offset_lens, c->lz_offset_freqs,
&c->os, &c->lz_offset_rebuild_info);
}
static bool
lzms_encode_length_symbol(struct lzms_compressor *c, unsigned sym)
{
return lzms_huffman_encode_symbol(sym, c->length_codewords,
c->length_lens, c->length_freqs,
&c->os, &c->length_rebuild_info);
}
static bool
lzms_encode_delta_offset_symbol(struct lzms_compressor *c, unsigned sym)
{
return lzms_huffman_encode_symbol(sym, c->delta_offset_codewords,
c->delta_offset_lens, c->delta_offset_freqs,
&c->os, &c->delta_offset_rebuild_info);
}
static bool
lzms_encode_delta_power_symbol(struct lzms_compressor *c, unsigned sym)
{
return lzms_huffman_encode_symbol(sym, c->delta_power_codewords,
c->delta_power_lens, c->delta_power_freqs,
&c->os, &c->delta_power_rebuild_info);
}
static void
lzms_update_fast_length_costs(struct lzms_compressor *c);
/*
* Encode a match length. If this causes the Huffman code for length symbols to
* be rebuilt, also update the length costs array used by the parser.
*/
static void
lzms_encode_length(struct lzms_compressor *c, u32 length)
{
unsigned slot = lzms_comp_get_length_slot(c, length);
if (lzms_encode_length_symbol(c, slot))
lzms_update_fast_length_costs(c);
lzms_write_bits(&c->os, length - lzms_length_slot_base[slot],
lzms_extra_length_bits[slot],
LZMS_MAX_EXTRA_LENGTH_BITS);
}
/* Encode the offset of an LZ match. */
static void
lzms_encode_lz_offset(struct lzms_compressor *c, u32 offset)
{
unsigned slot = lzms_comp_get_offset_slot(c, offset);
lzms_encode_lz_offset_symbol(c, slot);
lzms_write_bits(&c->os, offset - lzms_offset_slot_base[slot],
lzms_extra_offset_bits[slot],
LZMS_MAX_EXTRA_OFFSET_BITS);
}
/* Encode the raw offset of a delta match. */
static void
lzms_encode_delta_raw_offset(struct lzms_compressor *c, u32 raw_offset)
{
unsigned slot = lzms_comp_get_offset_slot(c, raw_offset);
lzms_encode_delta_offset_symbol(c, slot);
lzms_write_bits(&c->os, raw_offset - lzms_offset_slot_base[slot],
lzms_extra_offset_bits[slot],
LZMS_MAX_EXTRA_OFFSET_BITS);
}
/******************************************************************************
* Item encoding *
******************************************************************************/
/* Encode the specified item, which may be a literal or any type of match. */
static void
lzms_encode_item(struct lzms_compressor *c, u32 length, u32 source)
{
/* Main bit: 0 = literal, 1 = match */
int main_bit = (length > 1);
lzms_encode_main_bit(c, main_bit);
if (!main_bit) {
/* Literal */
unsigned literal = source;
lzms_encode_literal_symbol(c, literal);
} else {
/* Match */
/* Match bit: 0 = LZ match, 1 = delta match */
int match_bit = (source & DELTA_SOURCE_TAG) != 0;
lzms_encode_match_bit(c, match_bit);
if (!match_bit) {
/* LZ match */
/* LZ bit: 0 = explicit offset, 1 = repeat offset */
int lz_bit = (source < LZMS_NUM_LZ_REPS);
lzms_encode_lz_bit(c, lz_bit);
if (!lz_bit) {
/* Explicit offset LZ match */
u32 offset = source - (LZMS_NUM_LZ_REPS - 1);
lzms_encode_lz_offset(c, offset);
} else {
/* Repeat offset LZ match */
int rep_idx = source;
for (int i = 0; i < rep_idx; i++)
lzms_encode_lz_rep_bit(c, 1, i);
if (rep_idx < LZMS_NUM_LZ_REP_DECISIONS)
lzms_encode_lz_rep_bit(c, 0, rep_idx);
}
} else {
/* Delta match */
source &= ~DELTA_SOURCE_TAG;
/* Delta bit: 0 = explicit offset, 1 = repeat offset */
int delta_bit = (source < LZMS_NUM_DELTA_REPS);
lzms_encode_delta_bit(c, delta_bit);
if (!delta_bit) {
/* Explicit offset delta match */
u32 power = source >> DELTA_SOURCE_POWER_SHIFT;
u32 raw_offset = (source & DELTA_SOURCE_RAW_OFFSET_MASK) -
(LZMS_NUM_DELTA_REPS - 1);
lzms_encode_delta_power_symbol(c, power);
lzms_encode_delta_raw_offset(c, raw_offset);
} else {
/* Repeat offset delta match */
int rep_idx = source;
for (int i = 0; i < rep_idx; i++)
lzms_encode_delta_rep_bit(c, 1, i);
if (rep_idx < LZMS_NUM_DELTA_REP_DECISIONS)
lzms_encode_delta_rep_bit(c, 0, rep_idx);
}
}
/* Match length (encoded the same way for any match type) */
lzms_encode_length(c, length);
}
}
/* Encode a list of matches and literals chosen by the parsing algorithm. */
static void
lzms_encode_nonempty_item_list(struct lzms_compressor *c,
struct lzms_optimum_node *end_node)
{
/* Since we've stored at each node the item we took to arrive at that
* node, we can trace our chosen path in backwards order. However, for
* encoding we need to trace our chosen path in forwards order. To make
* this possible, the following loop moves the items from their
* destination nodes to their source nodes, which effectively reverses
* the path. (Think of it like reversing a singly-linked list.) */
struct lzms_optimum_node *cur_node = end_node;
struct lzms_item saved_item = cur_node->item;
do {
struct lzms_item item = saved_item;
if (cur_node->num_extra_items > 0) {
/* Handle an arrival via multi-item lookahead. */
unsigned i = 0;
struct lzms_optimum_node *orig_node = cur_node;
do {
cur_node -= item.length;
cur_node->item = item;
item = orig_node->extra_items[i];
} while (++i != orig_node->num_extra_items);
}
cur_node -= item.length;
saved_item = cur_node->item;
cur_node->item = item;
} while (cur_node != c->optimum_nodes);
/* Now trace the chosen path in forwards order, encoding each item. */
do {
lzms_encode_item(c, cur_node->item.length, cur_node->item.source);
cur_node += cur_node->item.length;
} while (cur_node != end_node);
}
static forceinline void
lzms_encode_item_list(struct lzms_compressor *c,
struct lzms_optimum_node *end_node)
{
if (end_node != c->optimum_nodes)
lzms_encode_nonempty_item_list(c, end_node);
}
/******************************************************************************
* Cost evaluation *
******************************************************************************/
/*
* If p is the predicted probability of the next bit being a 0, then the number
* of bits required to encode a 0 bit using a binary range encoder is the real
* number -log2(p), and the number of bits required to encode a 1 bit is the
* real number -log2(1 - p). To avoid computing either of these expressions at
* runtime, 'lzms_bit_costs' is a precomputed table that stores a mapping from
* probability to cost for each possible probability. Specifically, the array
* indices are the numerators of the possible probabilities in LZMS, where the
* denominators are LZMS_PROBABILITY_DENOMINATOR; and the stored costs are the
* bit costs multiplied by 1<<COST_SHIFT and rounded to the nearest integer.
* Furthermore, the values stored for 0% and 100% probabilities are equal to the
* adjacent values, since these probabilities are not actually permitted. This
* allows us to use the num_recent_zero_bits value from the
* lzms_probability_entry as the array index without fixing up these two special
* cases.
*/
static const u32 lzms_bit_costs[LZMS_PROBABILITY_DENOMINATOR + 1] = {
384, 384, 320, 283, 256, 235, 219, 204,
192, 181, 171, 163, 155, 147, 140, 134,
128, 122, 117, 112, 107, 103, 99, 94,
91, 87, 83, 80, 76, 73, 70, 67,
64, 61, 58, 56, 53, 51, 48, 46,
43, 41, 39, 37, 35, 33, 30, 29,
27, 25, 23, 21, 19, 17, 16, 14,
12, 11, 9, 8, 6, 4, 3, 1,
1
};
static void __attribute__((unused))
check_cost_shift(void)
{
/* lzms_bit_costs is hard-coded to the current COST_SHIFT. */
STATIC_ASSERT(COST_SHIFT == 6);
}
#if 0
#include <math.h>
static void
lzms_compute_bit_costs(void)
{
for (u32 i = 0; i <= LZMS_PROBABILITY_DENOMINATOR; i++) {
u32 prob = i;
if (prob == 0)
prob++;
else if (prob == LZMS_PROBABILITY_DENOMINATOR)
prob--;
lzms_bit_costs[i] = round(-log2((double)prob / LZMS_PROBABILITY_DENOMINATOR) *
(1 << COST_SHIFT));
}