Debian Codegraph @

src/org/tukaani/xz/lzma/LZMAEncoder.java

raw symbols SCIP
1 // SPDX-License-Identifier: 0BSD
2 // SPDX-FileCopyrightText: The XZ for Java authors and contributors
3 // SPDX-FileContributor: Lasse Collin <[email protected]>
4 // SPDX-FileContributor: Igor Pavlov <https://7-zip.org/>
5
6 package org.tukaani.xz.lzma;
7
8 import java.io.IOException;
9 import org.tukaani.xz.ArrayCache;
10 import org.tukaani.xz.lz.LZEncoder;
11 import org.tukaani.xz.lz.Matches;
12 import org.tukaani.xz.rangecoder.RangeEncoder;
13
14 public abstract class LZMAEncoder extends LZMACoder {
15 public static final int MODE_FAST = 1;
16 public static final int MODE_NORMAL = 2;
17
18 /**
19 * LZMA2 chunk is considered full when its uncompressed size exceeds
20 * {@code LZMA2_UNCOMPRESSED_LIMIT}.
21 * <p>
22 * A compressed LZMA2 chunk can hold 2 MiB of uncompressed data.
23 * A single LZMA symbol may indicate up to MATCH_LEN_MAX bytes
24 * of data, so the LZMA2 chunk is considered full when there is
25 * less space than MATCH_LEN_MAX bytes.
26 */
27 private static final int LZMA2_UNCOMPRESSED_LIMIT
28 = (2 << 20) - MATCH_LEN_MAX;
29
30 /**
31 * LZMA2 chunk is considered full when its compressed size exceeds
32 * {@code LZMA2_COMPRESSED_LIMIT}.
33 * <p>
34 * The maximum compressed size of a LZMA2 chunk is 64 KiB.
35 * A single LZMA symbol might use 20 bytes of space even though
36 * it usually takes just one byte or so. Two more bytes are needed
37 * for LZMA2 uncompressed chunks (see LZMA2OutputStream.writeChunk).
38 * Leave a little safety margin and use 26 bytes.
39 */
40 private static final int LZMA2_COMPRESSED_LIMIT = (64 << 10) - 26;
41
42 private static final int DIST_PRICE_UPDATE_INTERVAL = FULL_DISTANCES;
43 private static final int ALIGN_PRICE_UPDATE_INTERVAL = ALIGN_SIZE;
44
45 private final RangeEncoder rc;
46 final LZEncoder lz;
47 final LiteralEncoder literalEncoder;
48 final LengthEncoder matchLenEncoder;
49 final LengthEncoder repLenEncoder;
50 final int niceLen;
51
52 private int distPriceCount = 0;
53 private int alignPriceCount = 0;
54
55 private final int distSlotPricesSize;
56 private final int[][] distSlotPrices;
57 private final int[][] fullDistPrices
58 = new int[DIST_STATES][FULL_DISTANCES];
59 private final int[] alignPrices = new int[ALIGN_SIZE];
60
61 int back = 0;
62 int readAhead = -1;
63 private int uncompressedSize = 0;
64
65 public static int getMemoryUsage(int mode, int dictSize,
66 int extraSizeBefore, int mf) {
67 int m = 80;
68
69 switch (mode) {
70 case MODE_FAST:
71 m += LZMAEncoderFast.getMemoryUsage(
72 dictSize, extraSizeBefore, mf);
73 break;
74
75 case MODE_NORMAL:
76 m += LZMAEncoderNormal.getMemoryUsage(
77 dictSize, extraSizeBefore, mf);
78 break;
79
80 default:
81 throw new IllegalArgumentException();
82 }
83
84 return m;
85 }
86
87 public static LZMAEncoder getInstance(
88 RangeEncoder rc, int lc, int lp, int pb, int mode,
89 int dictSize, int extraSizeBefore,
90 int niceLen, int mf, int depthLimit,
91 ArrayCache arrayCache) {
92 switch (mode) {
93 case MODE_FAST:
94 return new LZMAEncoderFast(rc, lc, lp, pb,
95 dictSize, extraSizeBefore,
96 niceLen, mf, depthLimit,
97 arrayCache);
98
99 case MODE_NORMAL:
100 return new LZMAEncoderNormal(rc, lc, lp, pb,
101 dictSize, extraSizeBefore,
102 niceLen, mf, depthLimit,
103 arrayCache);
104 }
105
106 throw new IllegalArgumentException();
107 }
108
109 public void putArraysToCache(ArrayCache arrayCache) {
110 lz.putArraysToCache(arrayCache);
111 }
112
113 /**
114 * Gets an integer [0, 63] matching the highest two bits of an integer.
115 * This is like bit scan reverse (BSR) on x86 except that this also
116 * cares about the second highest bit.
117 */
118 public static int getDistSlot(int dist) {
119 if (dist <= DIST_MODEL_START && dist >= 0)
120 return dist;
121
122 int i = 31 - Integer.numberOfLeadingZeros(dist);
123 return (i << 1) + ((dist >>> (i - 1)) & 1);
124 }
125
126 /**
127 * Gets the next LZMA symbol.
128 * <p>
129 * There are three types of symbols: literal (a single byte),
130 * repeated match, and normal match. The symbol is indicated
131 * by the return value and by the variable {@code back}.
132 * <p>
133 * Literal: {@code back == -1} and return value is {@code 1}.
134 * The literal itself needs to be read from {@code lz} separately.
135 * <p>
136 * Repeated match: {@code back} is in the range [0, 3] and
137 * the return value is the length of the repeated match.
138 * <p>
139 * Normal match: {@code back - REPS} ({@code back - 4})
140 * is the distance of the match and the return value is the length
141 * of the match.
142 */
143 abstract int getNextSymbol();
144
145 LZMAEncoder(RangeEncoder rc, LZEncoder lz,
146 int lc, int lp, int pb, int dictSize, int niceLen) {
147 super(pb);
148 this.rc = rc;
149 this.lz = lz;
150 this.niceLen = niceLen;
151
152 literalEncoder = new LiteralEncoder(lc, lp);
153 matchLenEncoder = new LengthEncoder(pb, niceLen);
154 repLenEncoder = new LengthEncoder(pb, niceLen);
155
156 distSlotPricesSize = getDistSlot(dictSize - 1) + 1;
157 distSlotPrices = new int[DIST_STATES][distSlotPricesSize];
158
159 reset();
160 }
161
162 public LZEncoder getLZEncoder() {
163 return lz;
164 }
165
166 @Override
167 public void reset() {
168 super.reset();
169 literalEncoder.reset();
170 matchLenEncoder.reset();
171 repLenEncoder.reset();
172 distPriceCount = 0;
173 alignPriceCount = 0;
174
175 uncompressedSize += readAhead + 1;
176 readAhead = -1;
177 }
178
179 public int getUncompressedSize() {
180 return uncompressedSize;
181 }
182
183 public void resetUncompressedSize() {
184 uncompressedSize = 0;
185 }
186
187 /**
188 * Compress for LZMA1.
189 */
190 public void encodeForLZMA1() throws IOException {
191 if (!lz.isStarted() && !encodeInit())
192 return;
193
194 while (encodeSymbol()) {}
195 }
196
197 public void encodeLZMA1EndMarker() throws IOException {
198 // End of stream marker is encoded as a match with the maximum
199 // possible distance. The length is ignored by the decoder,
200 // but the minimum length has been used by the LZMA SDK.
201 //
202 // Distance is a 32-bit unsigned integer in LZMA.
203 // With Java's signed int, UINT32_MAX becomes -1.
204 int posState = (lz.getPos() - readAhead) & posMask;
205 rc.encodeBit(isMatch[state.get()], posState, 1);
206 rc.encodeBit(isRep, state.get(), 0);
207 encodeMatch(-1, MATCH_LEN_MIN, posState);
208 }
209
210 /**
211 * Compresses for LZMA2.
212 *
213 * @return true if the LZMA2 chunk became full, false otherwise
214 */
215 public boolean encodeForLZMA2() {
216 // LZMA2 uses RangeEncoderToBuffer so IOExceptions aren't possible.
217 try {
218 if (!lz.isStarted() && !encodeInit())
219 return false;
220
221 while (uncompressedSize <= LZMA2_UNCOMPRESSED_LIMIT
222 && rc.getPendingSize() <= LZMA2_COMPRESSED_LIMIT)
223 if (!encodeSymbol())
224 return false;
225 } catch (IOException e) {
226 throw new Error();
227 }
228
229 return true;
230 }
231
232 private boolean encodeInit() throws IOException {
233 assert readAhead == -1;
234 if (!lz.hasEnoughData(0))
235 return false;
236
237 // The first symbol must be a literal unless using
238 // a preset dictionary. This code isn't run if using
239 // a preset dictionary.
240 skip(1);
241 rc.encodeBit(isMatch[state.get()], 0, 0);
242 literalEncoder.encodeInit();
243
244 --readAhead;
245 assert readAhead == -1;
246
247 ++uncompressedSize;
248 assert uncompressedSize == 1;
249
250 return true;
251 }
252
253 private boolean encodeSymbol() throws IOException {
254 if (!lz.hasEnoughData(readAhead + 1))
255 return false;
256
257 int len = getNextSymbol();
258
259 assert readAhead >= 0;
260 int posState = (lz.getPos() - readAhead) & posMask;
261
262 if (back == -1) {
263 // Literal i.e. eight-bit byte
264 assert len == 1;
265 rc.encodeBit(isMatch[state.get()], posState, 0);
266 literalEncoder.encode();
267 } else {
268 // Some type of match
269 rc.encodeBit(isMatch[state.get()], posState, 1);
270 if (back < REPS) {
271 // Repeated match i.e. the same distance
272 // has been used earlier.
273 assert lz.getMatchLen(-readAhead, reps[back], len) == len;
274 rc.encodeBit(isRep, state.get(), 1);
275 encodeRepMatch(back, len, posState);
276 } else {
277 // Normal match
278 assert lz.getMatchLen(-readAhead, back - REPS, len) == len;
279 rc.encodeBit(isRep, state.get(), 0);
280 encodeMatch(back - REPS, len, posState);
281 }
282 }
283
284 readAhead -= len;
285 uncompressedSize += len;
286
287 return true;
288 }
289
290 private void encodeMatch(int dist, int len, int posState)
291 throws IOException {
292 state.updateMatch();
293 matchLenEncoder.encode(len, posState);
294
295 int distSlot = getDistSlot(dist);
296 rc.encodeBitTree(distSlots[getDistState(len)], distSlot);
297
298 if (distSlot >= DIST_MODEL_START) {
299 int footerBits = (distSlot >>> 1) - 1;
300 int base = (2 | (distSlot & 1)) << footerBits;
301 int distReduced = dist - base;
302
303 if (distSlot < DIST_MODEL_END) {
304 rc.encodeReverseBitTree(
305 distSpecial[distSlot - DIST_MODEL_START],
306 distReduced);
307 } else {
308 rc.encodeDirectBits(distReduced >>> ALIGN_BITS,
309 footerBits - ALIGN_BITS);
310 rc.encodeReverseBitTree(distAlign, distReduced & ALIGN_MASK);
311 --alignPriceCount;
312 }
313 }
314
315 reps[3] = reps[2];
316 reps[2] = reps[1];
317 reps[1] = reps[0];
318 reps[0] = dist;
319
320 --distPriceCount;
321 }
322
323 private void encodeRepMatch(int rep, int len, int posState)
324 throws IOException {
325 if (rep == 0) {
326 rc.encodeBit(isRep0, state.get(), 0);
327 rc.encodeBit(isRep0Long[state.get()], posState, len == 1 ? 0 : 1);
328 } else {
329 int dist = reps[rep];
330 rc.encodeBit(isRep0, state.get(), 1);
331
332 if (rep == 1) {
333 rc.encodeBit(isRep1, state.get(), 0);
334 } else {
335 rc.encodeBit(isRep1, state.get(), 1);
336 rc.encodeBit(isRep2, state.get(), rep - 2);
337
338 if (rep == 3)
339 reps[3] = reps[2];
340
341 reps[2] = reps[1];
342 }
343
344 reps[1] = reps[0];
345 reps[0] = dist;
346 }
347
348 if (len == 1) {
349 state.updateShortRep();
350 } else {
351 repLenEncoder.encode(len, posState);
352 state.updateLongRep();
353 }
354 }
355
356 Matches getMatches() {
357 ++readAhead;
358 Matches matches = lz.getMatches();
359 assert lz.verifyMatches(matches);
360 return matches;
361 }
362
363 void skip(int len) {
364 readAhead += len;
365 lz.skip(len);
366 }
367
368 int getAnyMatchPrice(State state, int posState) {
369 return RangeEncoder.getBitPrice(isMatch[state.get()][posState], 1);
370 }
371
372 int getNormalMatchPrice(int anyMatchPrice, State state) {
373 return anyMatchPrice
374 + RangeEncoder.getBitPrice(isRep[state.get()], 0);
375 }
376
377 int getAnyRepPrice(int anyMatchPrice, State state) {
378 return anyMatchPrice
379 + RangeEncoder.getBitPrice(isRep[state.get()], 1);
380 }
381
382 int getShortRepPrice(int anyRepPrice, State state, int posState) {
383 return anyRepPrice
384 + RangeEncoder.getBitPrice(isRep0[state.get()], 0)
385 + RangeEncoder.getBitPrice(isRep0Long[state.get()][posState],
386 0);
387 }
388
389 int getLongRepPrice(int anyRepPrice, int rep, State state, int posState) {
390 int price = anyRepPrice;
391
392 if (rep == 0) {
393 price += RangeEncoder.getBitPrice(isRep0[state.get()], 0)
394 + RangeEncoder.getBitPrice(
395 isRep0Long[state.get()][posState], 1);
396 } else {
397 price += RangeEncoder.getBitPrice(isRep0[state.get()], 1);
398
399 if (rep == 1)
400 price += RangeEncoder.getBitPrice(isRep1[state.get()], 0);
401 else
402 price += RangeEncoder.getBitPrice(isRep1[state.get()], 1)
403 + RangeEncoder.getBitPrice(isRep2[state.get()],
404 rep - 2);
405 }
406
407 return price;
408 }
409
410 int getLongRepAndLenPrice(int rep, int len, State state, int posState) {
411 int anyMatchPrice = getAnyMatchPrice(state, posState);
412 int anyRepPrice = getAnyRepPrice(anyMatchPrice, state);
413 int longRepPrice = getLongRepPrice(anyRepPrice, rep, state, posState);
414 return longRepPrice + repLenEncoder.getPrice(len, posState);
415 }
416
417 int getMatchAndLenPrice(int normalMatchPrice,
418 int dist, int len, int posState) {
419 int price = normalMatchPrice
420 + matchLenEncoder.getPrice(len, posState);
421 int distState = getDistState(len);
422
423 if (dist < FULL_DISTANCES) {
424 price += fullDistPrices[distState][dist];
425 } else {
426 // Note that distSlotPrices includes also
427 // the price of direct bits.
428 int distSlot = getDistSlot(dist);
429 price += distSlotPrices[distState][distSlot]
430 + alignPrices[dist & ALIGN_MASK];
431 }
432
433 return price;
434 }
435
436 private void updateDistPrices() {
437 distPriceCount = DIST_PRICE_UPDATE_INTERVAL;
438
439 for (int distState = 0; distState < DIST_STATES; ++distState) {
440 for (int distSlot = 0; distSlot < distSlotPricesSize; ++distSlot)
441 distSlotPrices[distState][distSlot]
442 = RangeEncoder.getBitTreePrice(
443 distSlots[distState], distSlot);
444
445 for (int distSlot = DIST_MODEL_END; distSlot < distSlotPricesSize;
446 ++distSlot) {
447 int count = (distSlot >>> 1) - 1 - ALIGN_BITS;
448 distSlotPrices[distState][distSlot]
449 += RangeEncoder.getDirectBitsPrice(count);
450 }
451
452 for (int dist = 0; dist < DIST_MODEL_START; ++dist)
453 fullDistPrices[distState][dist]
454 = distSlotPrices[distState][dist];
455 }
456
457 int dist = DIST_MODEL_START;
458 for (int distSlot = DIST_MODEL_START; distSlot < DIST_MODEL_END;
459 ++distSlot) {
460 int footerBits = (distSlot >>> 1) - 1;
461 int base = (2 | (distSlot & 1)) << footerBits;
462
463 int limit = distSpecial[distSlot - DIST_MODEL_START].length;
464 for (int i = 0; i < limit; ++i) {
465 int distReduced = dist - base;
466 int price = RangeEncoder.getReverseBitTreePrice(
467 distSpecial[distSlot - DIST_MODEL_START],
468 distReduced);
469
470 for (int distState = 0; distState < DIST_STATES; ++distState)
471 fullDistPrices[distState][dist]
472 = distSlotPrices[distState][distSlot] + price;
473
474 ++dist;
475 }
476 }
477
478 assert dist == FULL_DISTANCES;
479 }
480
481 private void updateAlignPrices() {
482 alignPriceCount = ALIGN_PRICE_UPDATE_INTERVAL;
483
484 for (int i = 0; i < ALIGN_SIZE; ++i)
485 alignPrices[i] = RangeEncoder.getReverseBitTreePrice(distAlign,
486 i);
487 }
488
489 /**
490 * Updates the lookup tables used for calculating match distance
491 * and length prices. The updating is skipped for performance reasons
492 * if the tables haven't changed much since the previous update.
493 */
494 void updatePrices() {
495 if (distPriceCount <= 0)
496 updateDistPrices();
497
498 if (alignPriceCount <= 0)
499 updateAlignPrices();
500
501 matchLenEncoder.updatePrices();
502 repLenEncoder.updatePrices();
503 }
504
505
506 class LiteralEncoder extends LiteralCoder {
507 private final LiteralSubencoder[] subencoders;
508
509 LiteralEncoder(int lc, int lp) {
510 super(lc, lp);
511
512 subencoders = new LiteralSubencoder[1 << (lc + lp)];
513 for (int i = 0; i < subencoders.length; ++i)
514 subencoders[i] = new LiteralSubencoder();
515 }
516
517 void reset() {
518 for (int i = 0; i < subencoders.length; ++i)
519 subencoders[i].reset();
520 }
521
522 void encodeInit() throws IOException {
523 // When encoding the first byte of the stream, there is
524 // no previous byte in the dictionary so the encode function
525 // wouldn't work.
526 assert readAhead >= 0;
527 subencoders[0].encode();
528 }
529
530 void encode() throws IOException {
531 assert readAhead >= 0;
532 int i = getSubcoderIndex(lz.getByte(1 + readAhead),
533 lz.getPos() - readAhead);
534 subencoders[i].encode();
535 }
536
537 int getPrice(int curByte, int matchByte,
538 int prevByte, int pos, State state) {
539 int price = RangeEncoder.getBitPrice(
540 isMatch[state.get()][pos & posMask], 0);
541
542 int i = getSubcoderIndex(prevByte, pos);
543 price += state.isLiteral()
544 ? subencoders[i].getNormalPrice(curByte)
545 : subencoders[i].getMatchedPrice(curByte, matchByte);
546
547 return price;
548 }
549
550 private class LiteralSubencoder extends LiteralSubcoder {
551 void encode() throws IOException {
552 int symbol = lz.getByte(readAhead) | 0x100;
553
554 if (state.isLiteral()) {
555 int subencoderIndex;
556 int bit;
557
558 do {
559 subencoderIndex = symbol >>> 8;
560 bit = (symbol >>> 7) & 1;
561 rc.encodeBit(probs, subencoderIndex, bit);
562 symbol <<= 1;
563 } while (symbol < 0x10000);
564
565 } else {
566 int matchByte = lz.getByte(reps[0] + 1 + readAhead);
567 int offset = 0x100;
568 int subencoderIndex;
569 int matchBit;
570 int bit;
571
572 do {
573 matchByte <<= 1;
574 matchBit = matchByte & offset;
575 subencoderIndex = offset + matchBit + (symbol >>> 8);
576 bit = (symbol >>> 7) & 1;
577 rc.encodeBit(probs, subencoderIndex, bit);
578 symbol <<= 1;
579 offset &= ~(matchByte ^ symbol);
580 } while (symbol < 0x10000);
581 }
582
583 state.updateLiteral();
584 }
585
586 int getNormalPrice(int symbol) {
587 int price = 0;
588 int subencoderIndex;
589 int bit;
590
591 symbol |= 0x100;
592
593 do {
594 subencoderIndex = symbol >>> 8;
595 bit = (symbol >>> 7) & 1;
596 price += RangeEncoder.getBitPrice(probs[subencoderIndex],
597 bit);
598 symbol <<= 1;
599 } while (symbol < (0x100 << 8));
600
601 return price;
602 }
603
604 int getMatchedPrice(int symbol, int matchByte) {
605 int price = 0;
606 int offset = 0x100;
607 int subencoderIndex;
608 int matchBit;
609 int bit;
610
611 symbol |= 0x100;
612
613 do {
614 matchByte <<= 1;
615 matchBit = matchByte & offset;
616 subencoderIndex = offset + matchBit + (symbol >>> 8);
617 bit = (symbol >>> 7) & 1;
618 price += RangeEncoder.getBitPrice(probs[subencoderIndex],
619 bit);
620 symbol <<= 1;
621 offset &= ~(matchByte ^ symbol);
622 } while (symbol < (0x100 << 8));
623
624 return price;
625 }
626 }
627 }
628
629
630 class LengthEncoder extends LengthCoder {
631 /**
632 * The prices are updated after at least
633 * {@code PRICE_UPDATE_INTERVAL} many lengths
634 * have been encoded with the same posState.
635 */
636 private static final int PRICE_UPDATE_INTERVAL = 32; // FIXME?
637
638 private final int[] counters;
639 private final int[][] prices;
640
641 LengthEncoder(int pb, int niceLen) {
642 int posStates = 1 << pb;
643 counters = new int[posStates];
644
645 // Always allocate at least LOW_SYMBOLS + MID_SYMBOLS because
646 // it makes updatePrices slightly simpler. The prices aren't
647 // usually needed anyway if niceLen < 18.
648 int lenSymbols = Math.max(niceLen - MATCH_LEN_MIN + 1,
649 LOW_SYMBOLS + MID_SYMBOLS);
650 prices = new int[posStates][lenSymbols];
651 }
652
653 @Override
654 void reset() {
655 super.reset();
656
657 // Reset counters to zero to force price update before
658 // the prices are needed.
659 for (int i = 0; i < counters.length; ++i)
660 counters[i] = 0;
661 }
662
663 void encode(int len, int posState) throws IOException {
664 len -= MATCH_LEN_MIN;
665
666 if (len < LOW_SYMBOLS) {
667 rc.encodeBit(choice, 0, 0);
668 rc.encodeBitTree(low[posState], len);
669 } else {
670 rc.encodeBit(choice, 0, 1);
671 len -= LOW_SYMBOLS;
672
673 if (len < MID_SYMBOLS) {
674 rc.encodeBit(choice, 1, 0);
675 rc.encodeBitTree(mid[posState], len);
676 } else {
677 rc.encodeBit(choice, 1, 1);
678 rc.encodeBitTree(high, len - MID_SYMBOLS);
679 }
680 }
681
682 --counters[posState];
683 }
684
685 int getPrice(int len, int posState) {
686 return prices[posState][len - MATCH_LEN_MIN];
687 }
688
689 void updatePrices() {
690 for (int posState = 0; posState < counters.length; ++posState) {
691 if (counters[posState] <= 0) {
692 counters[posState] = PRICE_UPDATE_INTERVAL;
693 updatePrices(posState);
694 }
695 }
696 }
697
698 private void updatePrices(int posState) {
699 int choice0Price = RangeEncoder.getBitPrice(choice[0], 0);
700
701 int i = 0;
702 for (; i < LOW_SYMBOLS; ++i)
703 prices[posState][i] = choice0Price
704 + RangeEncoder.getBitTreePrice(low[posState], i);
705
706 choice0Price = RangeEncoder.getBitPrice(choice[0], 1);
707 int choice1Price = RangeEncoder.getBitPrice(choice[1], 0);
708
709 for (; i < LOW_SYMBOLS + MID_SYMBOLS; ++i)
710 prices[posState][i] = choice0Price + choice1Price
711 + RangeEncoder.getBitTreePrice(mid[posState],
712 i - LOW_SYMBOLS);
713
714 choice1Price = RangeEncoder.getBitPrice(choice[1], 1);
715
716 for (; i < prices[posState].length; ++i)
717 prices[posState][i] = choice0Price + choice1Price
718 + RangeEncoder.getBitTreePrice(high, i - LOW_SYMBOLS
719 - MID_SYMBOLS);
720 }
721 }
722 }