Debian Codegraph @

src/org/tukaani/xz/LZMA2Options.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
5 package org.tukaani.xz;
6
7 import java.io.InputStream;
8 import java.io.IOException;
9 import org.tukaani.xz.lz.LZEncoder;
10 import org.tukaani.xz.lzma.LZMAEncoder;
11
12 /**
13 * LZMA2 compression options.
14 * <p>
15 * While this allows setting the LZMA2 compression options in detail,
16 * often you only need {@code LZMA2Options()} or
17 * {@code LZMA2Options(int)}.
18 */
19 public final class LZMA2Options extends FilterOptions {
20 /**
21 * Minimum valid compression preset level is 0.
22 */
23 public static final int PRESET_MIN = 0;
24
25 /**
26 * Maximum valid compression preset level is 9.
27 */
28 public static final int PRESET_MAX = 9;
29
30 /**
31 * Default compression preset level is 6.
32 */
33 public static final int PRESET_DEFAULT = 6;
34
35 /**
36 * Minimum dictionary size is 4 KiB.
37 */
38 public static final int DICT_SIZE_MIN = 4096;
39
40 /**
41 * Maximum dictionary size for compression is 768 MiB.
42 * <p>
43 * The decompressor supports bigger dictionaries, up to almost 2 GiB.
44 * With HC4 the encoder would support dictionaries bigger than 768 MiB.
45 * The 768 MiB limit comes from the current implementation of BT4 where
46 * we would otherwise hit the limits of signed ints in array indexing.
47 * <p>
48 * If you really need bigger dictionary for decompression,
49 * use {@link LZMA2InputStream} directly.
50 */
51 public static final int DICT_SIZE_MAX = 768 << 20;
52
53 /**
54 * The default dictionary size is 8 MiB.
55 */
56 public static final int DICT_SIZE_DEFAULT = 8 << 20;
57
58 /**
59 * Maximum value for lc + lp is 4.
60 */
61 public static final int LC_LP_MAX = 4;
62
63 /**
64 * The default number of literal context bits is 3.
65 */
66 public static final int LC_DEFAULT = 3;
67
68 /**
69 * The default number of literal position bits is 0.
70 */
71 public static final int LP_DEFAULT = 0;
72
73 /**
74 * Maximum value for pb is 4.
75 */
76 public static final int PB_MAX = 4;
77
78 /**
79 * The default number of position bits is 2.
80 */
81 public static final int PB_DEFAULT = 2;
82
83 /**
84 * Compression mode: uncompressed.
85 * The data is wrapped into a LZMA2 stream without compression.
86 */
87 public static final int MODE_UNCOMPRESSED = 0;
88
89 /**
90 * Compression mode: fast.
91 * This is usually combined with a hash chain match finder.
92 */
93 public static final int MODE_FAST = LZMAEncoder.MODE_FAST;
94
95 /**
96 * Compression mode: normal.
97 * This is usually combined with a binary tree match finder.
98 */
99 public static final int MODE_NORMAL = LZMAEncoder.MODE_NORMAL;
100
101 /**
102 * Minimum value for {@code niceLen} is 8.
103 */
104 public static final int NICE_LEN_MIN = 8;
105
106 /**
107 * Maximum value for {@code niceLen} is 273.
108 */
109 public static final int NICE_LEN_MAX = 273;
110
111 /**
112 * Match finder: Hash Chain 2-3-4
113 */
114 public static final int MF_HC4 = LZEncoder.MF_HC4;
115
116 /**
117 * Match finder: Binary tree 2-3-4
118 */
119 public static final int MF_BT4 = LZEncoder.MF_BT4;
120
121 private static final int[] presetToDictSize = {
122 1 << 18, 1 << 20, 1 << 21, 1 << 22, 1 << 22,
123 1 << 23, 1 << 23, 1 << 24, 1 << 25, 1 << 26 };
124
125 private static final int[] presetToDepthLimit = { 4, 8, 24, 48 };
126
127 private int dictSize;
128 private byte[] presetDict = null;
129 private int lc;
130 private int lp;
131 private int pb;
132 private int mode;
133 private int niceLen;
134 private int mf;
135 private int depthLimit;
136
137 /**
138 * Creates new LZMA2 options and sets them to the default values.
139 * This is equivalent to {@code LZMA2Options(PRESET_DEFAULT)}.
140 */
141 public LZMA2Options() {
142 try {
143 setPreset(PRESET_DEFAULT);
144 } catch (UnsupportedOptionsException e) {
145 assert false;
146 throw new RuntimeException();
147 }
148 }
149
150 /**
151 * Creates new LZMA2 options and sets them to the given preset.
152 *
153 * @throws UnsupportedOptionsException
154 * {@code preset} is not supported
155 */
156 public LZMA2Options(int preset) throws UnsupportedOptionsException {
157 setPreset(preset);
158 }
159
160 /**
161 * Creates new LZMA2 options and sets them to the given custom values.
162 *
163 * @throws UnsupportedOptionsException
164 * unsupported options were specified
165 */
166 public LZMA2Options(int dictSize, int lc, int lp, int pb, int mode,
167 int niceLen, int mf, int depthLimit)
168 throws UnsupportedOptionsException {
169 setDictSize(dictSize);
170 setLcLp(lc, lp);
171 setPb(pb);
172 setMode(mode);
173 setNiceLen(niceLen);
174 setMatchFinder(mf);
175 setDepthLimit(depthLimit);
176 }
177
178 /**
179 * Sets the compression options to the given preset.
180 * <p>
181 * The presets 0-3 are fast presets with medium compression.
182 * The presets 4-6 are fairly slow presets with high compression.
183 * The default preset ({@code PRESET_DEFAULT}) is 6.
184 * <p>
185 * The presets 7-9 are like the preset 6 but use bigger dictionaries
186 * and have higher compressor and decompressor memory requirements.
187 * Unless the uncompressed size of the file exceeds 8&nbsp;MiB,
188 * 16&nbsp;MiB, or 32&nbsp;MiB, it is waste of memory to use the
189 * presets 7, 8, or 9, respectively.
190 *
191 * @throws UnsupportedOptionsException
192 * {@code preset} is not supported
193 */
194 public void setPreset(int preset) throws UnsupportedOptionsException {
195 if (preset < 0 || preset > 9)
196 throw new UnsupportedOptionsException(
197 "Unsupported preset: " + preset);
198
199 lc = LC_DEFAULT;
200 lp = LP_DEFAULT;
201 pb = PB_DEFAULT;
202 dictSize = presetToDictSize[preset];
203
204 if (preset <= 3) {
205 mode = MODE_FAST;
206 mf = MF_HC4;
207 niceLen = preset <= 1 ? 128 : NICE_LEN_MAX;
208 depthLimit = presetToDepthLimit[preset];
209 } else {
210 mode = MODE_NORMAL;
211 mf = MF_BT4;
212 niceLen = (preset == 4) ? 16 : (preset == 5) ? 32 : 64;
213 depthLimit = 0;
214 }
215 }
216
217 /**
218 * Sets the dictionary size in bytes.
219 * <p>
220 * The dictionary (or history buffer) holds the most recently seen
221 * uncompressed data. Bigger dictionary usually means better compression.
222 * However, using a dictioanary bigger than the size of the uncompressed
223 * data is waste of memory.
224 * <p>
225 * Any value in the range [DICT_SIZE_MIN, DICT_SIZE_MAX] is valid,
226 * but sizes of 2^n and 2^n&nbsp;+&nbsp;2^(n-1) bytes are somewhat
227 * recommended.
228 *
229 * @throws UnsupportedOptionsException
230 * {@code dictSize} is not supported
231 */
232 public void setDictSize(int dictSize) throws UnsupportedOptionsException {
233 if (dictSize < DICT_SIZE_MIN)
234 throw new UnsupportedOptionsException(
235 "LZMA2 dictionary size must be at least 4 KiB: "
236 + dictSize + " B");
237
238 if (dictSize > DICT_SIZE_MAX)
239 throw new UnsupportedOptionsException(
240 "LZMA2 dictionary size must not exceed "
241 + (DICT_SIZE_MAX >> 20) + " MiB: " + dictSize + " B");
242
243 this.dictSize = dictSize;
244 }
245
246 /**
247 * Gets the dictionary size in bytes.
248 */
249 public int getDictSize() {
250 return dictSize;
251 }
252
253 /**
254 * Sets a preset dictionary. Use null to disable the use of
255 * a preset dictionary. By default there is no preset dictionary.
256 * <p>
257 * <b>The .xz format doesn't support a preset dictionary for now.
258 * Do not set a preset dictionary unless you use raw LZMA2.</b>
259 * <p>
260 * Preset dictionary can be useful when compressing many similar,
261 * relatively small chunks of data independently from each other.
262 * A preset dictionary should contain typical strings that occur in
263 * the files being compressed. The most probable strings should be
264 * near the end of the preset dictionary. The preset dictionary used
265 * for compression is also needed for decompression.
266 */
267 public void setPresetDict(byte[] presetDict) {
268 this.presetDict = presetDict;
269 }
270
271 /**
272 * Gets the preset dictionary.
273 */
274 public byte[] getPresetDict() {
275 return presetDict;
276 }
277
278 /**
279 * Sets the number of literal context bits and literal position bits.
280 * <p>
281 * The sum of {@code lc} and {@code lp} is limited to 4.
282 * Trying to exceed it will throw an exception. This function lets
283 * you change both at the same time.
284 *
285 * @throws UnsupportedOptionsException
286 * {@code lc} and {@code lp}
287 * are invalid
288 */
289 public void setLcLp(int lc, int lp) throws UnsupportedOptionsException {
290 if (lc < 0 || lp < 0 || lc > LC_LP_MAX || lp > LC_LP_MAX
291 || lc + lp > LC_LP_MAX)
292 throw new UnsupportedOptionsException(
293 "lc + lp must not exceed " + LC_LP_MAX + ": "
294 + lc + " + " + lp);
295
296 this.lc = lc;
297 this.lp = lp;
298 }
299
300 /**
301 * Sets the number of literal context bits.
302 * <p>
303 * All bytes that cannot be encoded as matches are encoded as literals.
304 * That is, literals are simply 8-bit bytes that are encoded one at
305 * a time.
306 * <p>
307 * The literal coding makes an assumption that the highest {@code lc}
308 * bits of the previous uncompressed byte correlate with the next byte.
309 * For example, in typical English text, an upper-case letter is often
310 * followed by a lower-case letter, and a lower-case letter is usually
311 * followed by another lower-case letter. In the US-ASCII character set,
312 * the highest three bits are 010 for upper-case letters and 011 for
313 * lower-case letters. When {@code lc} is at least 3, the literal
314 * coding can take advantage of this property in the uncompressed data.
315 * <p>
316 * The default value (3) is usually good. If you want maximum compression,
317 * try {@code setLc(4)}. Sometimes it helps a little, and sometimes it
318 * makes compression worse. If it makes it worse, test for example
319 * {@code setLc(2)} too.
320 *
321 * @throws UnsupportedOptionsException
322 * {@code lc} is invalid, or the sum
323 * of {@code lc} and {@code lp}
324 * exceed LC_LP_MAX
325 */
326 public void setLc(int lc) throws UnsupportedOptionsException {
327 setLcLp(lc, lp);
328 }
329
330 /**
331 * Sets the number of literal position bits.
332 * <p>
333 * This affets what kind of alignment in the uncompressed data is
334 * assumed when encoding literals. See {@link #setPb(int) setPb} for
335 * more information about alignment.
336 *
337 * @throws UnsupportedOptionsException
338 * {@code lp} is invalid, or the sum
339 * of {@code lc} and {@code lp}
340 * exceed LC_LP_MAX
341 */
342 public void setLp(int lp) throws UnsupportedOptionsException {
343 setLcLp(lc, lp);
344 }
345
346 /**
347 * Gets the number of literal context bits.
348 */
349 public int getLc() {
350 return lc;
351 }
352
353 /**
354 * Gets the number of literal position bits.
355 */
356 public int getLp() {
357 return lp;
358 }
359
360 /**
361 * Sets the number of position bits.
362 * <p>
363 * This affects what kind of alignment in the uncompressed data is
364 * assumed in general. The default (2) means four-byte alignment
365 * (2^{@code pb} = 2^2 = 4), which is often a good choice when
366 * there's no better guess.
367 * <p>
368 * When the alignment is known, setting the number of position bits
369 * accordingly may reduce the file size a little. For example with text
370 * files having one-byte alignment (US-ASCII, ISO-8859-*, UTF-8), using
371 * {@code setPb(0)} can improve compression slightly. For UTF-16
372 * text, {@code setPb(1)} is a good choice. If the alignment is
373 * an odd number like 3 bytes, {@code setPb(0)} might be the best
374 * choice.
375 * <p>
376 * Even though the assumed alignment can be adjusted with
377 * {@code setPb} and {@code setLp}, LZMA2 still slightly favors
378 * 16-byte alignment. It might be worth taking into account when designing
379 * file formats that are likely to be often compressed with LZMA2.
380 *
381 * @throws UnsupportedOptionsException
382 * {@code pb} is invalid
383 */
384 public void setPb(int pb) throws UnsupportedOptionsException {
385 if (pb < 0 || pb > PB_MAX)
386 throw new UnsupportedOptionsException(
387 "pb must not exceed " + PB_MAX + ": " + pb);
388
389 this.pb = pb;
390 }
391
392 /**
393 * Gets the number of position bits.
394 */
395 public int getPb() {
396 return pb;
397 }
398
399 /**
400 * Sets the compression mode.
401 * <p>
402 * This specifies the method to analyze the data produced by
403 * a match finder. The default is {@code MODE_FAST} for presets
404 * 0-3 and {@code MODE_NORMAL} for presets 4-9.
405 * <p>
406 * Usually {@code MODE_FAST} is used with Hash Chain match finders
407 * and {@code MODE_NORMAL} with Binary Tree match finders. This is
408 * also what the presets do.
409 * <p>
410 * The special mode {@code MODE_UNCOMPRESSED} doesn't try to
411 * compress the data at all (and doesn't use a match finder) and will
412 * simply wrap it in uncompressed LZMA2 chunks.
413 *
414 * @throws UnsupportedOptionsException
415 * {@code mode} is not supported
416 */
417 public void setMode(int mode) throws UnsupportedOptionsException {
418 if (mode < MODE_UNCOMPRESSED || mode > MODE_NORMAL)
419 throw new UnsupportedOptionsException(
420 "Unsupported compression mode: " + mode);
421
422 this.mode = mode;
423 }
424
425 /**
426 * Gets the compression mode.
427 */
428 public int getMode() {
429 return mode;
430 }
431
432 /**
433 * Sets the nice length of matches.
434 * Once a match of at least {@code niceLen} bytes is found,
435 * the algorithm stops looking for better matches. Higher values tend
436 * to give better compression at the expense of speed. The default
437 * depends on the preset.
438 *
439 * @throws UnsupportedOptionsException
440 * {@code niceLen} is invalid
441 */
442 public void setNiceLen(int niceLen) throws UnsupportedOptionsException {
443 if (niceLen < NICE_LEN_MIN)
444 throw new UnsupportedOptionsException(
445 "Minimum nice length of matches is "
446 + NICE_LEN_MIN + " bytes: " + niceLen);
447
448 if (niceLen > NICE_LEN_MAX)
449 throw new UnsupportedOptionsException(
450 "Maximum nice length of matches is " + NICE_LEN_MAX
451 + ": " + niceLen);
452
453 this.niceLen = niceLen;
454 }
455
456 /**
457 * Gets the nice length of matches.
458 */
459 public int getNiceLen() {
460 return niceLen;
461 }
462
463 /**
464 * Sets the match finder type.
465 * <p>
466 * Match finder has a major effect on compression speed, memory usage,
467 * and compression ratio. Usually Hash Chain match finders are faster
468 * than Binary Tree match finders. The default depends on the preset:
469 * 0-3 use {@code MF_HC4} and 4-9 use {@code MF_BT4}.
470 *
471 * @throws UnsupportedOptionsException
472 * {@code mf} is not supported
473 */
474 public void setMatchFinder(int mf) throws UnsupportedOptionsException {
475 if (mf != MF_HC4 && mf != MF_BT4)
476 throw new UnsupportedOptionsException(
477 "Unsupported match finder: " + mf);
478
479 this.mf = mf;
480 }
481
482 /**
483 * Gets the match finder type.
484 */
485 public int getMatchFinder() {
486 return mf;
487 }
488
489 /**
490 * Sets the match finder search depth limit.
491 * <p>
492 * The default is a special value of {@code 0} which indicates that
493 * the depth limit should be automatically calculated by the selected
494 * match finder from the nice length of matches.
495 * <p>
496 * Reasonable depth limit for Hash Chain match finders is 4-100 and
497 * 16-1000 for Binary Tree match finders. Using very high values can
498 * make the compressor extremely slow with some files. Avoid settings
499 * higher than 1000 unless you are prepared to interrupt the compression
500 * in case it is taking far too long.
501 *
502 * @throws UnsupportedOptionsException
503 * {@code depthLimit} is invalid
504 */
505 public void setDepthLimit(int depthLimit)
506 throws UnsupportedOptionsException {
507 if (depthLimit < 0)
508 throw new UnsupportedOptionsException(
509 "Depth limit cannot be negative: " + depthLimit);
510
511 this.depthLimit = depthLimit;
512 }
513
514 /**
515 * Gets the match finder search depth limit.
516 */
517 public int getDepthLimit() {
518 return depthLimit;
519 }
520
521 @Override
522 public int getEncoderMemoryUsage() {
523 return (mode == MODE_UNCOMPRESSED)
524 ? UncompressedLZMA2OutputStream.getMemoryUsage()
525 : LZMA2OutputStream.getMemoryUsage(this);
526 }
527
528 @Override
529 public FinishableOutputStream getOutputStream(FinishableOutputStream out,
530 ArrayCache arrayCache) {
531 if (mode == MODE_UNCOMPRESSED)
532 return new UncompressedLZMA2OutputStream(out, arrayCache);
533
534 return new LZMA2OutputStream(out, this, arrayCache);
535 }
536
537 /**
538 * Gets how much memory the LZMA2 decoder will need to decompress the data
539 * that was encoded with these options and stored in a .xz file.
540 * <p>
541 * The returned value may bigger than the value returned by a direct call
542 * to {@link LZMA2InputStream#getMemoryUsage(int)} if the dictionary size
543 * is not 2^n or 2^n&nbsp;+&nbsp;2^(n-1) bytes. This is because the .xz
544 * headers store the dictionary size in such a format and other values
545 * are rounded up to the next such value. Such rounding is harmess except
546 * it might waste some memory if an unusual dictionary size is used.
547 * <p>
548 * If you use raw LZMA2 streams and unusual dictioanary size, call
549 * {@link LZMA2InputStream#getMemoryUsage} directly to get raw decoder
550 * memory requirements.
551 */
552 @Override
553 public int getDecoderMemoryUsage() {
554 // Round the dictionary size up to the next 2^n or 2^n + 2^(n-1).
555 int d = dictSize - 1;
556 d |= d >>> 2;
557 d |= d >>> 3;
558 d |= d >>> 4;
559 d |= d >>> 8;
560 d |= d >>> 16;
561 return LZMA2InputStream.getMemoryUsage(d + 1);
562 }
563
564 @Override
565 public InputStream getInputStream(InputStream in, ArrayCache arrayCache)
566 throws IOException {
567 return new LZMA2InputStream(in, dictSize, presetDict, arrayCache);
568 }
569
570 @Override
571 FilterEncoder getFilterEncoder() {
572 return new LZMA2Encoder(this);
573 }
574
575 @Override
576 public Object clone() {
577 try {
578 return super.clone();
579 } catch (CloneNotSupportedException e) {
580 assert false;
581 throw new RuntimeException();
582 }
583 }
584 }