1 From: Alexandros C. Couloumbis <alex@ozo.com>
2 Subject: fs: add jffs2/lzma support (not activated by default yet)
4 lede-commit: c2c88d315fa0e881f8b19da07b62859b915b11b2
5 Signed-off-by: Alexandros C. Couloumbis <alex@ozo.com>
8 fs/jffs2/Makefile | 3 +
10 fs/jffs2/compr.h | 10 +-
11 fs/jffs2/compr_lzma.c | 128 +++
12 fs/jffs2/super.c | 33 +-
13 include/linux/lzma.h | 62 ++
14 include/linux/lzma/LzFind.h | 115 +++
15 include/linux/lzma/LzHash.h | 54 +
16 include/linux/lzma/LzmaDec.h | 231 +++++
17 include/linux/lzma/LzmaEnc.h | 80 ++
18 include/linux/lzma/Types.h | 226 +++++
19 include/uapi/linux/jffs2.h | 1 +
22 lib/lzma/LzFind.c | 761 ++++++++++++++
23 lib/lzma/LzmaDec.c | 999 +++++++++++++++++++
24 lib/lzma/LzmaEnc.c | 2271 ++++++++++++++++++++++++++++++++++++++++++
25 lib/lzma/Makefile | 7 +
26 19 files changed, 5008 insertions(+), 6 deletions(-)
27 create mode 100644 fs/jffs2/compr_lzma.c
28 create mode 100644 include/linux/lzma.h
29 create mode 100644 include/linux/lzma/LzFind.h
30 create mode 100644 include/linux/lzma/LzHash.h
31 create mode 100644 include/linux/lzma/LzmaDec.h
32 create mode 100644 include/linux/lzma/LzmaEnc.h
33 create mode 100644 include/linux/lzma/Types.h
34 create mode 100644 lib/lzma/LzFind.c
35 create mode 100644 lib/lzma/LzmaDec.c
36 create mode 100644 lib/lzma/LzmaEnc.c
37 create mode 100644 lib/lzma/Makefile
39 diff --git a/fs/jffs2/Kconfig b/fs/jffs2/Kconfig
40 index d8bb6c411e96..74bf4b162e36 100644
41 --- a/fs/jffs2/Kconfig
42 +++ b/fs/jffs2/Kconfig
43 @@ -139,6 +139,15 @@ config JFFS2_LZO
44 This feature was added in July, 2007. Say 'N' if you need
45 compatibility with older bootloaders or kernels.
48 + bool "JFFS2 LZMA compression support" if JFFS2_COMPRESSION_OPTIONS
49 + select LZMA_COMPRESS
50 + select LZMA_DECOMPRESS
54 + JFFS2 wrapper to the LZMA C SDK
57 bool "JFFS2 RTIME compression support" if JFFS2_COMPRESSION_OPTIONS
59 diff --git a/fs/jffs2/Makefile b/fs/jffs2/Makefile
60 index 60e5d49ca03e..23ba6efd1f3f 100644
61 --- a/fs/jffs2/Makefile
62 +++ b/fs/jffs2/Makefile
63 @@ -18,4 +18,7 @@ jffs2-$(CONFIG_JFFS2_RUBIN) += compr_rubin.o
64 jffs2-$(CONFIG_JFFS2_RTIME) += compr_rtime.o
65 jffs2-$(CONFIG_JFFS2_ZLIB) += compr_zlib.o
66 jffs2-$(CONFIG_JFFS2_LZO) += compr_lzo.o
67 +jffs2-$(CONFIG_JFFS2_LZMA) += compr_lzma.o
68 jffs2-$(CONFIG_JFFS2_SUMMARY) += summary.o
70 +CFLAGS_compr_lzma.o += -Iinclude/linux -Ilib/lzma
71 diff --git a/fs/jffs2/compr.c b/fs/jffs2/compr.c
72 index 4849a4c9a0e2..6ec806abb7b9 100644
73 --- a/fs/jffs2/compr.c
74 +++ b/fs/jffs2/compr.c
75 @@ -378,6 +378,9 @@ int __init jffs2_compressors_init(void)
76 #ifdef CONFIG_JFFS2_LZO
79 +#ifdef CONFIG_JFFS2_LZMA
82 /* Setting default compression mode */
83 #ifdef CONFIG_JFFS2_CMODE_NONE
84 jffs2_compression_mode = JFFS2_COMPR_MODE_NONE;
85 @@ -401,6 +404,9 @@ int __init jffs2_compressors_init(void)
86 int jffs2_compressors_exit(void)
88 /* Unregistering compressors */
89 +#ifdef CONFIG_JFFS2_LZMA
92 #ifdef CONFIG_JFFS2_LZO
95 diff --git a/fs/jffs2/compr.h b/fs/jffs2/compr.h
96 index 5e91d578f4ed..32db2e1ec610 100644
97 --- a/fs/jffs2/compr.h
98 +++ b/fs/jffs2/compr.h
100 #define JFFS2_DYNRUBIN_PRIORITY 20
101 #define JFFS2_LZARI_PRIORITY 30
102 #define JFFS2_RTIME_PRIORITY 50
103 -#define JFFS2_ZLIB_PRIORITY 60
104 -#define JFFS2_LZO_PRIORITY 80
106 +#define JFFS2_LZMA_PRIORITY 70
107 +#define JFFS2_ZLIB_PRIORITY 80
108 +#define JFFS2_LZO_PRIORITY 90
110 #define JFFS2_RUBINMIPS_DISABLED /* RUBINs will be used only */
111 #define JFFS2_DYNRUBIN_DISABLED /* for decompression */
112 @@ -101,5 +101,9 @@ void jffs2_zlib_exit(void);
113 int jffs2_lzo_init(void);
114 void jffs2_lzo_exit(void);
116 +#ifdef CONFIG_JFFS2_LZMA
117 +int jffs2_lzma_init(void);
118 +void jffs2_lzma_exit(void);
121 #endif /* __JFFS2_COMPR_H__ */
122 diff --git a/fs/jffs2/compr_lzma.c b/fs/jffs2/compr_lzma.c
124 index 000000000000..0fe3b75d7dcc
126 +++ b/fs/jffs2/compr_lzma.c
129 + * JFFS2 -- Journalling Flash File System, Version 2.
131 + * For licensing information, see the file 'LICENCE' in this directory.
133 + * JFFS2 wrapper to the LZMA C SDK
137 +#include <linux/lzma.h>
141 + static DEFINE_MUTEX(deflate_mutex);
145 +Byte propsEncoded[LZMA_PROPS_SIZE];
146 +SizeT propsSize = sizeof(propsEncoded);
148 +STATIC void lzma_free_workspace(void)
150 + LzmaEnc_Destroy(p, &lzma_alloc, &lzma_alloc);
153 +STATIC int INIT lzma_alloc_workspace(CLzmaEncProps *props)
155 + if ((p = (CLzmaEncHandle *)LzmaEnc_Create(&lzma_alloc)) == NULL)
157 + PRINT_ERROR("Failed to allocate lzma deflate workspace\n");
161 + if (LzmaEnc_SetProps(p, props) != SZ_OK)
163 + lzma_free_workspace();
167 + if (LzmaEnc_WriteProperties(p, propsEncoded, &propsSize) != SZ_OK)
169 + lzma_free_workspace();
176 +STATIC int jffs2_lzma_compress(unsigned char *data_in, unsigned char *cpage_out,
177 + uint32_t *sourcelen, uint32_t *dstlen)
179 + SizeT compress_size = (SizeT)(*dstlen);
183 + mutex_lock(&deflate_mutex);
186 + ret = LzmaEnc_MemEncode(p, cpage_out, &compress_size, data_in, *sourcelen,
187 + 0, NULL, &lzma_alloc, &lzma_alloc);
190 + mutex_unlock(&deflate_mutex);
196 + *dstlen = (uint32_t)compress_size;
201 +STATIC int jffs2_lzma_decompress(unsigned char *data_in, unsigned char *cpage_out,
202 + uint32_t srclen, uint32_t destlen)
205 + SizeT dl = (SizeT)destlen;
206 + SizeT sl = (SizeT)srclen;
207 + ELzmaStatus status;
209 + ret = LzmaDecode(cpage_out, &dl, data_in, &sl, propsEncoded,
210 + propsSize, LZMA_FINISH_ANY, &status, &lzma_alloc);
212 + if (ret != SZ_OK || status == LZMA_STATUS_NOT_FINISHED || dl != (SizeT)destlen)
218 +static struct jffs2_compressor jffs2_lzma_comp = {
219 + .priority = JFFS2_LZMA_PRIORITY,
221 + .compr = JFFS2_COMPR_LZMA,
222 + .compress = &jffs2_lzma_compress,
223 + .decompress = &jffs2_lzma_decompress,
227 +int INIT jffs2_lzma_init(void)
230 + CLzmaEncProps props;
231 + LzmaEncProps_Init(&props);
233 + props.dictSize = LZMA_BEST_DICT(0x2000);
234 + props.level = LZMA_BEST_LEVEL;
235 + props.lc = LZMA_BEST_LC;
236 + props.lp = LZMA_BEST_LP;
237 + props.pb = LZMA_BEST_PB;
238 + props.fb = LZMA_BEST_FB;
240 + ret = lzma_alloc_workspace(&props);
244 + ret = jffs2_register_compressor(&jffs2_lzma_comp);
246 + lzma_free_workspace();
251 +void jffs2_lzma_exit(void)
253 + jffs2_unregister_compressor(&jffs2_lzma_comp);
254 + lzma_free_workspace();
256 diff --git a/fs/jffs2/super.c b/fs/jffs2/super.c
257 index 5ef21f4c4c77..62e730216e7d 100644
258 --- a/fs/jffs2/super.c
259 +++ b/fs/jffs2/super.c
260 @@ -372,14 +372,41 @@ static int __init init_jffs2_fs(void)
261 BUILD_BUG_ON(sizeof(struct jffs2_raw_inode) != 68);
262 BUILD_BUG_ON(sizeof(struct jffs2_raw_summary) != 32);
264 - pr_info("version 2.2."
265 + pr_info("version 2.2"
266 #ifdef CONFIG_JFFS2_FS_WRITEBUFFER
269 #ifdef CONFIG_JFFS2_SUMMARY
273 - " © 2001-2006 Red Hat, Inc.\n");
274 +#ifdef CONFIG_JFFS2_ZLIB
277 +#ifdef CONFIG_JFFS2_LZO
280 +#ifdef CONFIG_JFFS2_LZMA
283 +#ifdef CONFIG_JFFS2_RTIME
286 +#ifdef CONFIG_JFFS2_RUBIN
289 +#ifdef CONFIG_JFFS2_CMODE_NONE
292 +#ifdef CONFIG_JFFS2_CMODE_PRIORITY
293 + " (CMODE_PRIORITY)"
295 +#ifdef CONFIG_JFFS2_CMODE_SIZE
298 +#ifdef CONFIG_JFFS2_CMODE_FAVOURLZO
299 + " (CMODE_FAVOURLZO)"
301 + " (c) 2001-2006 Red Hat, Inc.\n");
303 jffs2_inode_cachep = kmem_cache_create("jffs2_i",
304 sizeof(struct jffs2_inode_info),
305 diff --git a/include/linux/lzma.h b/include/linux/lzma.h
307 index 000000000000..5f31334dfc31
309 +++ b/include/linux/lzma.h
315 + #include <linux/kernel.h>
316 + #include <linux/sched.h>
317 + #include <linux/slab.h>
318 + #include <linux/vmalloc.h>
319 + #include <linux/init.h>
320 + #define LZMA_MALLOC vmalloc
321 + #define LZMA_FREE vfree
322 + #define PRINT_ERROR(msg) printk(KERN_WARNING #msg)
323 + #define INIT __init
324 + #define STATIC static
326 + #include <stdint.h>
327 + #include <stdlib.h>
329 + #include <unistd.h>
330 + #include <string.h>
331 + #include <asm/types.h>
333 + #include <linux/jffs2.h>
335 + extern int page_size;
336 + #define PAGE_SIZE page_size
338 + #define LZMA_MALLOC malloc
339 + #define LZMA_FREE free
340 + #define PRINT_ERROR(msg) fprintf(stderr, msg)
345 +#include "lzma/LzmaDec.h"
346 +#include "lzma/LzmaEnc.h"
348 +#define LZMA_BEST_LEVEL (9)
349 +#define LZMA_BEST_LC (0)
350 +#define LZMA_BEST_LP (0)
351 +#define LZMA_BEST_PB (0)
352 +#define LZMA_BEST_FB (273)
354 +#define LZMA_BEST_DICT(n) (((int)((n) / 2)) * 2)
356 +static void *p_lzma_malloc(void *p, size_t size)
361 + return LZMA_MALLOC(size);
364 +static void p_lzma_free(void *p, void *address)
366 + if (address != NULL)
367 + LZMA_FREE(address);
370 +static ISzAlloc lzma_alloc = {p_lzma_malloc, p_lzma_free};
373 diff --git a/include/linux/lzma/LzFind.h b/include/linux/lzma/LzFind.h
375 index 000000000000..010c4b92ba33
377 +++ b/include/linux/lzma/LzFind.h
379 +/* LzFind.h -- Match finder for LZ algorithms
380 +2009-04-22 : Igor Pavlov : Public domain */
391 +typedef UInt32 CLzRef;
393 +typedef struct _CMatchFinder
401 + UInt32 cyclicBufferPos;
402 + UInt32 cyclicBufferSize; /* it must be = (historySize + 1) */
404 + UInt32 matchMaxLen;
411 + ISeqInStream *stream;
412 + int streamEndWasReached;
415 + UInt32 keepSizeBefore;
416 + UInt32 keepSizeAfter;
418 + UInt32 numHashBytes;
420 + size_t directInputRem;
423 + UInt32 historySize;
424 + UInt32 fixedHashSize;
425 + UInt32 hashSizeSum;
431 +#define Inline_MatchFinder_GetPointerToCurrentPos(p) ((p)->buffer)
432 +#define Inline_MatchFinder_GetIndexByte(p, index) ((p)->buffer[(Int32)(index)])
434 +#define Inline_MatchFinder_GetNumAvailableBytes(p) ((p)->streamPos - (p)->pos)
436 +int MatchFinder_NeedMove(CMatchFinder *p);
437 +Byte *MatchFinder_GetPointerToCurrentPos(CMatchFinder *p);
438 +void MatchFinder_MoveBlock(CMatchFinder *p);
439 +void MatchFinder_ReadIfRequired(CMatchFinder *p);
441 +void MatchFinder_Construct(CMatchFinder *p);
444 + historySize <= 3 GB
445 + keepAddBufferBefore + matchMaxLen + keepAddBufferAfter < 511MB
447 +int MatchFinder_Create(CMatchFinder *p, UInt32 historySize,
448 + UInt32 keepAddBufferBefore, UInt32 matchMaxLen, UInt32 keepAddBufferAfter,
450 +void MatchFinder_Free(CMatchFinder *p, ISzAlloc *alloc);
451 +void MatchFinder_Normalize3(UInt32 subValue, CLzRef *items, UInt32 numItems);
452 +void MatchFinder_ReduceOffsets(CMatchFinder *p, UInt32 subValue);
454 +UInt32 * GetMatchesSpec1(UInt32 lenLimit, UInt32 curMatch, UInt32 pos, const Byte *buffer, CLzRef *son,
455 + UInt32 _cyclicBufferPos, UInt32 _cyclicBufferSize, UInt32 _cutValue,
456 + UInt32 *distances, UInt32 maxLen);
460 + Mf_GetNumAvailableBytes_Func must be called before each Mf_GetMatchLen_Func.
461 + Mf_GetPointerToCurrentPos_Func's result must be used only before any other function
464 +typedef void (*Mf_Init_Func)(void *object);
465 +typedef Byte (*Mf_GetIndexByte_Func)(void *object, Int32 index);
466 +typedef UInt32 (*Mf_GetNumAvailableBytes_Func)(void *object);
467 +typedef const Byte * (*Mf_GetPointerToCurrentPos_Func)(void *object);
468 +typedef UInt32 (*Mf_GetMatches_Func)(void *object, UInt32 *distances);
469 +typedef void (*Mf_Skip_Func)(void *object, UInt32);
471 +typedef struct _IMatchFinder
474 + Mf_GetIndexByte_Func GetIndexByte;
475 + Mf_GetNumAvailableBytes_Func GetNumAvailableBytes;
476 + Mf_GetPointerToCurrentPos_Func GetPointerToCurrentPos;
477 + Mf_GetMatches_Func GetMatches;
481 +void MatchFinder_CreateVTable(CMatchFinder *p, IMatchFinder *vTable);
483 +void MatchFinder_Init(CMatchFinder *p);
484 +UInt32 Bt3Zip_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances);
485 +UInt32 Hc3Zip_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances);
486 +void Bt3Zip_MatchFinder_Skip(CMatchFinder *p, UInt32 num);
487 +void Hc3Zip_MatchFinder_Skip(CMatchFinder *p, UInt32 num);
494 diff --git a/include/linux/lzma/LzHash.h b/include/linux/lzma/LzHash.h
496 index 000000000000..f3e89966cc70
498 +++ b/include/linux/lzma/LzHash.h
500 +/* LzHash.h -- HASH functions for LZ algorithms
501 +2009-02-07 : Igor Pavlov : Public domain */
506 +#define kHash2Size (1 << 10)
507 +#define kHash3Size (1 << 16)
508 +#define kHash4Size (1 << 20)
510 +#define kFix3HashSize (kHash2Size)
511 +#define kFix4HashSize (kHash2Size + kHash3Size)
512 +#define kFix5HashSize (kHash2Size + kHash3Size + kHash4Size)
514 +#define HASH2_CALC hashValue = cur[0] | ((UInt32)cur[1] << 8);
516 +#define HASH3_CALC { \
517 + UInt32 temp = p->crc[cur[0]] ^ cur[1]; \
518 + hash2Value = temp & (kHash2Size - 1); \
519 + hashValue = (temp ^ ((UInt32)cur[2] << 8)) & p->hashMask; }
521 +#define HASH4_CALC { \
522 + UInt32 temp = p->crc[cur[0]] ^ cur[1]; \
523 + hash2Value = temp & (kHash2Size - 1); \
524 + hash3Value = (temp ^ ((UInt32)cur[2] << 8)) & (kHash3Size - 1); \
525 + hashValue = (temp ^ ((UInt32)cur[2] << 8) ^ (p->crc[cur[3]] << 5)) & p->hashMask; }
527 +#define HASH5_CALC { \
528 + UInt32 temp = p->crc[cur[0]] ^ cur[1]; \
529 + hash2Value = temp & (kHash2Size - 1); \
530 + hash3Value = (temp ^ ((UInt32)cur[2] << 8)) & (kHash3Size - 1); \
531 + hash4Value = (temp ^ ((UInt32)cur[2] << 8) ^ (p->crc[cur[3]] << 5)); \
532 + hashValue = (hash4Value ^ (p->crc[cur[4]] << 3)) & p->hashMask; \
533 + hash4Value &= (kHash4Size - 1); }
535 +/* #define HASH_ZIP_CALC hashValue = ((cur[0] | ((UInt32)cur[1] << 8)) ^ p->crc[cur[2]]) & 0xFFFF; */
536 +#define HASH_ZIP_CALC hashValue = ((cur[2] | ((UInt32)cur[0] << 8)) ^ p->crc[cur[1]]) & 0xFFFF;
539 +#define MT_HASH2_CALC \
540 + hash2Value = (p->crc[cur[0]] ^ cur[1]) & (kHash2Size - 1);
542 +#define MT_HASH3_CALC { \
543 + UInt32 temp = p->crc[cur[0]] ^ cur[1]; \
544 + hash2Value = temp & (kHash2Size - 1); \
545 + hash3Value = (temp ^ ((UInt32)cur[2] << 8)) & (kHash3Size - 1); }
547 +#define MT_HASH4_CALC { \
548 + UInt32 temp = p->crc[cur[0]] ^ cur[1]; \
549 + hash2Value = temp & (kHash2Size - 1); \
550 + hash3Value = (temp ^ ((UInt32)cur[2] << 8)) & (kHash3Size - 1); \
551 + hash4Value = (temp ^ ((UInt32)cur[2] << 8) ^ (p->crc[cur[3]] << 5)) & (kHash4Size - 1); }
554 diff --git a/include/linux/lzma/LzmaDec.h b/include/linux/lzma/LzmaDec.h
556 index 000000000000..bf7f084ba3dd
558 +++ b/include/linux/lzma/LzmaDec.h
560 +/* LzmaDec.h -- LZMA Decoder
561 +2009-02-07 : Igor Pavlov : Public domain */
563 +#ifndef __LZMA_DEC_H
564 +#define __LZMA_DEC_H
572 +/* #define _LZMA_PROB32 */
573 +/* _LZMA_PROB32 can increase the speed on some CPUs,
574 + but memory usage for CLzmaDec::probs will be doubled in that case */
577 +#define CLzmaProb UInt32
579 +#define CLzmaProb UInt16
583 +/* ---------- LZMA Properties ---------- */
585 +#define LZMA_PROPS_SIZE 5
587 +typedef struct _CLzmaProps
589 + unsigned lc, lp, pb;
593 +/* LzmaProps_Decode - decodes properties
596 + SZ_ERROR_UNSUPPORTED - Unsupported properties
599 +SRes LzmaProps_Decode(CLzmaProps *p, const Byte *data, unsigned size);
602 +/* ---------- LZMA Decoder state ---------- */
604 +/* LZMA_REQUIRED_INPUT_MAX = number of required input bytes for worst case.
605 + Num bits = log2((2^11 / 31) ^ 22) + 26 < 134 + 26 = 160; */
607 +#define LZMA_REQUIRED_INPUT_MAX 20
615 + UInt32 range, code;
618 + UInt32 processedPos;
619 + UInt32 checkDicSize;
622 + unsigned remainLen;
626 + unsigned tempBufSize;
627 + Byte tempBuf[LZMA_REQUIRED_INPUT_MAX];
630 +#define LzmaDec_Construct(p) { (p)->dic = 0; (p)->probs = 0; }
632 +void LzmaDec_Init(CLzmaDec *p);
634 +/* There are two types of LZMA streams:
635 + 0) Stream with end mark. That end mark adds about 6 bytes to compressed size.
636 + 1) Stream without end mark. You must know exact uncompressed size to decompress such stream. */
640 + LZMA_FINISH_ANY, /* finish at any point */
641 + LZMA_FINISH_END /* block must be finished at the end */
644 +/* ELzmaFinishMode has meaning only if the decoding reaches output limit !!!
646 + You must use LZMA_FINISH_END, when you know that current output buffer
647 + covers last bytes of block. In other cases you must use LZMA_FINISH_ANY.
649 + If LZMA decoder sees end marker before reaching output limit, it returns SZ_OK,
650 + and output value of destLen will be less than output buffer size limit.
651 + You can check status result also.
653 + You can use multiple checks to test data integrity after full decompression:
654 + 1) Check Result and "status" variable.
655 + 2) Check that output(destLen) = uncompressedSize, if you know real uncompressedSize.
656 + 3) Check that output(srcLen) = compressedSize, if you know real compressedSize.
657 + You must use correct finish mode in that case. */
661 + LZMA_STATUS_NOT_SPECIFIED, /* use main error code instead */
662 + LZMA_STATUS_FINISHED_WITH_MARK, /* stream was finished with end mark. */
663 + LZMA_STATUS_NOT_FINISHED, /* stream was not finished */
664 + LZMA_STATUS_NEEDS_MORE_INPUT, /* you must provide more input bytes */
665 + LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK /* there is probability that stream was finished without end mark */
668 +/* ELzmaStatus is used only as output value for function call */
671 +/* ---------- Interfaces ---------- */
673 +/* There are 3 levels of interfaces:
674 + 1) Dictionary Interface
675 + 2) Buffer Interface
676 + 3) One Call Interface
677 + You can select any of these interfaces, but don't mix functions from different
678 + groups for same object. */
681 +/* There are two variants to allocate state for Dictionary Interface:
682 + 1) LzmaDec_Allocate / LzmaDec_Free
683 + 2) LzmaDec_AllocateProbs / LzmaDec_FreeProbs
684 + You can use variant 2, if you set dictionary buffer manually.
685 + For Buffer Interface you must always use variant 1.
687 +LzmaDec_Allocate* can return:
689 + SZ_ERROR_MEM - Memory allocation error
690 + SZ_ERROR_UNSUPPORTED - Unsupported properties
693 +SRes LzmaDec_AllocateProbs(CLzmaDec *p, const Byte *props, unsigned propsSize, ISzAlloc *alloc);
694 +void LzmaDec_FreeProbs(CLzmaDec *p, ISzAlloc *alloc);
696 +SRes LzmaDec_Allocate(CLzmaDec *state, const Byte *prop, unsigned propsSize, ISzAlloc *alloc);
697 +void LzmaDec_Free(CLzmaDec *state, ISzAlloc *alloc);
699 +/* ---------- Dictionary Interface ---------- */
701 +/* You can use it, if you want to eliminate the overhead for data copying from
702 + dictionary to some other external buffer.
703 + You must work with CLzmaDec variables directly in this interface.
708 + for (each new stream)
711 + while (it needs more decompression)
713 + LzmaDec_DecodeToDic()
714 + use data from CLzmaDec::dic and update CLzmaDec::dicPos
720 +/* LzmaDec_DecodeToDic
722 + The decoding to internal dictionary buffer (CLzmaDec::dic).
723 + You must manually update CLzmaDec::dicPos, if it reaches CLzmaDec::dicBufSize !!!
726 + It has meaning only if the decoding reaches output limit (dicLimit).
727 + LZMA_FINISH_ANY - Decode just dicLimit bytes.
728 + LZMA_FINISH_END - Stream must be finished after dicLimit.
733 + LZMA_STATUS_FINISHED_WITH_MARK
734 + LZMA_STATUS_NOT_FINISHED
735 + LZMA_STATUS_NEEDS_MORE_INPUT
736 + LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK
737 + SZ_ERROR_DATA - Data error
740 +SRes LzmaDec_DecodeToDic(CLzmaDec *p, SizeT dicLimit,
741 + const Byte *src, SizeT *srcLen, ELzmaFinishMode finishMode, ELzmaStatus *status);
744 +/* ---------- Buffer Interface ---------- */
746 +/* It's zlib-like interface.
747 + See LzmaDec_DecodeToDic description for information about STEPS and return results,
748 + but you must use LzmaDec_DecodeToBuf instead of LzmaDec_DecodeToDic and you don't need
749 + to work with CLzmaDec variables manually.
752 + It has meaning only if the decoding reaches output limit (*destLen).
753 + LZMA_FINISH_ANY - Decode just destLen bytes.
754 + LZMA_FINISH_END - Stream must be finished after (*destLen).
757 +SRes LzmaDec_DecodeToBuf(CLzmaDec *p, Byte *dest, SizeT *destLen,
758 + const Byte *src, SizeT *srcLen, ELzmaFinishMode finishMode, ELzmaStatus *status);
761 +/* ---------- One Call Interface ---------- */
766 + It has meaning only if the decoding reaches output limit (*destLen).
767 + LZMA_FINISH_ANY - Decode just destLen bytes.
768 + LZMA_FINISH_END - Stream must be finished after (*destLen).
773 + LZMA_STATUS_FINISHED_WITH_MARK
774 + LZMA_STATUS_NOT_FINISHED
775 + LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK
776 + SZ_ERROR_DATA - Data error
777 + SZ_ERROR_MEM - Memory allocation error
778 + SZ_ERROR_UNSUPPORTED - Unsupported properties
779 + SZ_ERROR_INPUT_EOF - It needs more bytes in input buffer (src).
782 +SRes LzmaDecode(Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen,
783 + const Byte *propData, unsigned propSize, ELzmaFinishMode finishMode,
784 + ELzmaStatus *status, ISzAlloc *alloc);
791 diff --git a/include/linux/lzma/LzmaEnc.h b/include/linux/lzma/LzmaEnc.h
793 index 000000000000..200d60eb83cd
795 +++ b/include/linux/lzma/LzmaEnc.h
797 +/* LzmaEnc.h -- LZMA Encoder
798 +2009-02-07 : Igor Pavlov : Public domain */
800 +#ifndef __LZMA_ENC_H
801 +#define __LZMA_ENC_H
809 +#define LZMA_PROPS_SIZE 5
811 +typedef struct _CLzmaEncProps
813 + int level; /* 0 <= level <= 9 */
814 + UInt32 dictSize; /* (1 << 12) <= dictSize <= (1 << 27) for 32-bit version
815 + (1 << 12) <= dictSize <= (1 << 30) for 64-bit version
816 + default = (1 << 24) */
817 + int lc; /* 0 <= lc <= 8, default = 3 */
818 + int lp; /* 0 <= lp <= 4, default = 0 */
819 + int pb; /* 0 <= pb <= 4, default = 2 */
820 + int algo; /* 0 - fast, 1 - normal, default = 1 */
821 + int fb; /* 5 <= fb <= 273, default = 32 */
822 + int btMode; /* 0 - hashChain Mode, 1 - binTree mode - normal, default = 1 */
823 + int numHashBytes; /* 2, 3 or 4, default = 4 */
824 + UInt32 mc; /* 1 <= mc <= (1 << 30), default = 32 */
825 + unsigned writeEndMark; /* 0 - do not write EOPM, 1 - write EOPM, default = 0 */
826 + int numThreads; /* 1 or 2, default = 2 */
829 +void LzmaEncProps_Init(CLzmaEncProps *p);
830 +void LzmaEncProps_Normalize(CLzmaEncProps *p);
831 +UInt32 LzmaEncProps_GetDictSize(const CLzmaEncProps *props2);
834 +/* ---------- CLzmaEncHandle Interface ---------- */
836 +/* LzmaEnc_* functions can return the following exit codes:
839 + SZ_ERROR_MEM - Memory allocation error
840 + SZ_ERROR_PARAM - Incorrect paramater in props
841 + SZ_ERROR_WRITE - Write callback error.
842 + SZ_ERROR_PROGRESS - some break from progress callback
843 + SZ_ERROR_THREAD - errors in multithreading functions (only for Mt version)
846 +typedef void * CLzmaEncHandle;
848 +CLzmaEncHandle LzmaEnc_Create(ISzAlloc *alloc);
849 +void LzmaEnc_Destroy(CLzmaEncHandle p, ISzAlloc *alloc, ISzAlloc *allocBig);
850 +SRes LzmaEnc_SetProps(CLzmaEncHandle p, const CLzmaEncProps *props);
851 +SRes LzmaEnc_WriteProperties(CLzmaEncHandle p, Byte *properties, SizeT *size);
852 +SRes LzmaEnc_Encode(CLzmaEncHandle p, ISeqOutStream *outStream, ISeqInStream *inStream,
853 + ICompressProgress *progress, ISzAlloc *alloc, ISzAlloc *allocBig);
854 +SRes LzmaEnc_MemEncode(CLzmaEncHandle p, Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen,
855 + int writeEndMark, ICompressProgress *progress, ISzAlloc *alloc, ISzAlloc *allocBig);
857 +/* ---------- One Call Interface ---------- */
862 + SZ_ERROR_MEM - Memory allocation error
863 + SZ_ERROR_PARAM - Incorrect paramater
864 + SZ_ERROR_OUTPUT_EOF - output buffer overflow
865 + SZ_ERROR_THREAD - errors in multithreading functions (only for Mt version)
868 +SRes LzmaEncode(Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen,
869 + const CLzmaEncProps *props, Byte *propsEncoded, SizeT *propsSize, int writeEndMark,
870 + ICompressProgress *progress, ISzAlloc *alloc, ISzAlloc *allocBig);
877 diff --git a/include/linux/lzma/Types.h b/include/linux/lzma/Types.h
879 index 000000000000..4751acde0722
881 +++ b/include/linux/lzma/Types.h
883 +/* Types.h -- Basic types
884 +2009-11-23 : Igor Pavlov : Public domain */
886 +#ifndef __7Z_TYPES_H
887 +#define __7Z_TYPES_H
892 +#include <windows.h>
895 +#ifndef EXTERN_C_BEGIN
897 +#define EXTERN_C_BEGIN extern "C" {
898 +#define EXTERN_C_END }
900 +#define EXTERN_C_BEGIN
901 +#define EXTERN_C_END
909 +#define SZ_ERROR_DATA 1
910 +#define SZ_ERROR_MEM 2
911 +#define SZ_ERROR_CRC 3
912 +#define SZ_ERROR_UNSUPPORTED 4
913 +#define SZ_ERROR_PARAM 5
914 +#define SZ_ERROR_INPUT_EOF 6
915 +#define SZ_ERROR_OUTPUT_EOF 7
916 +#define SZ_ERROR_READ 8
917 +#define SZ_ERROR_WRITE 9
918 +#define SZ_ERROR_PROGRESS 10
919 +#define SZ_ERROR_FAIL 11
920 +#define SZ_ERROR_THREAD 12
922 +#define SZ_ERROR_ARCHIVE 16
923 +#define SZ_ERROR_NO_ARCHIVE 17
934 +#define RINOK(x) { int __result__ = (x); if (__result__ != 0) return __result__; }
937 +typedef unsigned char Byte;
938 +typedef short Int16;
939 +typedef unsigned short UInt16;
941 +#ifdef _LZMA_UINT32_IS_ULONG
943 +typedef unsigned long UInt32;
946 +typedef unsigned int UInt32;
949 +#ifdef _SZ_NO_INT_64
951 +/* define _SZ_NO_INT_64, if your compiler doesn't support 64-bit integers.
952 + NOTES: Some code will work incorrectly in that case! */
955 +typedef unsigned long UInt64;
959 +#if defined(_MSC_VER) || defined(__BORLANDC__)
960 +typedef __int64 Int64;
961 +typedef unsigned __int64 UInt64;
963 +typedef long long int Int64;
964 +typedef unsigned long long int UInt64;
969 +#ifdef _LZMA_NO_SYSTEM_SIZE_T
970 +typedef UInt32 SizeT;
972 +typedef size_t SizeT;
981 +#define MY_STD_CALL __stdcall
988 +#if _MSC_VER >= 1300
989 +#define MY_NO_INLINE __declspec(noinline)
991 +#define MY_NO_INLINE
994 +#define MY_CDECL __cdecl
995 +#define MY_FAST_CALL __fastcall
1000 +#define MY_FAST_CALL
1005 +/* The following interfaces use first parameter as pointer to structure */
1009 + SRes (*Read)(void *p, void *buf, size_t *size);
1010 + /* if (input(*size) != 0 && output(*size) == 0) means end_of_stream.
1011 + (output(*size) < input(*size)) is allowed */
1014 +/* it can return SZ_ERROR_INPUT_EOF */
1015 +SRes SeqInStream_Read(ISeqInStream *stream, void *buf, size_t size);
1016 +SRes SeqInStream_Read2(ISeqInStream *stream, void *buf, size_t size, SRes errorType);
1017 +SRes SeqInStream_ReadByte(ISeqInStream *stream, Byte *buf);
1021 + size_t (*Write)(void *p, const void *buf, size_t size);
1022 + /* Returns: result - the number of actually written bytes.
1023 + (result < size) means error */
1035 + SRes (*Read)(void *p, void *buf, size_t *size); /* same as ISeqInStream::Read */
1036 + SRes (*Seek)(void *p, Int64 *pos, ESzSeek origin);
1041 + SRes (*Look)(void *p, void **buf, size_t *size);
1042 + /* if (input(*size) != 0 && output(*size) == 0) means end_of_stream.
1043 + (output(*size) > input(*size)) is not allowed
1044 + (output(*size) < input(*size)) is allowed */
1045 + SRes (*Skip)(void *p, size_t offset);
1046 + /* offset must be <= output(*size) of Look */
1048 + SRes (*Read)(void *p, void *buf, size_t *size);
1049 + /* reads directly (without buffer). It's same as ISeqInStream::Read */
1050 + SRes (*Seek)(void *p, Int64 *pos, ESzSeek origin);
1053 +SRes LookInStream_LookRead(ILookInStream *stream, void *buf, size_t *size);
1054 +SRes LookInStream_SeekTo(ILookInStream *stream, UInt64 offset);
1056 +/* reads via ILookInStream::Read */
1057 +SRes LookInStream_Read2(ILookInStream *stream, void *buf, size_t size, SRes errorType);
1058 +SRes LookInStream_Read(ILookInStream *stream, void *buf, size_t size);
1060 +#define LookToRead_BUF_SIZE (1 << 14)
1065 + ISeekInStream *realStream;
1068 + Byte buf[LookToRead_BUF_SIZE];
1071 +void LookToRead_CreateVTable(CLookToRead *p, int lookahead);
1072 +void LookToRead_Init(CLookToRead *p);
1077 + ILookInStream *realStream;
1080 +void SecToLook_CreateVTable(CSecToLook *p);
1085 + ILookInStream *realStream;
1088 +void SecToRead_CreateVTable(CSecToRead *p);
1092 + SRes (*Progress)(void *p, UInt64 inSize, UInt64 outSize);
1093 + /* Returns: result. (result != SZ_OK) means break.
1094 + Value (UInt64)(Int64)-1 for size means unknown value. */
1095 +} ICompressProgress;
1099 + void *(*Alloc)(void *p, size_t size);
1100 + void (*Free)(void *p, void *address); /* address can be 0 */
1103 +#define IAlloc_Alloc(p, size) (p)->Alloc((p), size)
1104 +#define IAlloc_Free(p, a) (p)->Free((p), a)
1109 diff --git a/include/uapi/linux/jffs2.h b/include/uapi/linux/jffs2.h
1110 index a18b719f49d4..f3431a5ff4ff 100644
1111 --- a/include/uapi/linux/jffs2.h
1112 +++ b/include/uapi/linux/jffs2.h
1114 #define JFFS2_COMPR_DYNRUBIN 0x05
1115 #define JFFS2_COMPR_ZLIB 0x06
1116 #define JFFS2_COMPR_LZO 0x07
1117 +#define JFFS2_COMPR_LZMA 0x08
1118 /* Compatibility flags. */
1119 #define JFFS2_COMPAT_MASK 0xc000 /* What do to if an unknown nodetype is found */
1120 #define JFFS2_NODE_ACCURATE 0x2000
1121 diff --git a/lib/Kconfig b/lib/Kconfig
1122 index 260a80e313b9..2e20b2b1ba02 100644
1125 @@ -241,6 +241,12 @@ config LZ4_DECOMPRESS
1127 source "lib/xz/Kconfig"
1129 +config LZMA_COMPRESS
1132 +config LZMA_DECOMPRESS
1136 # These all provide a common interface (hence the apparent duplication with
1137 # ZLIB_INFLATE; DECOMPRESS_GZIP is just a wrapper.)
1138 diff --git a/lib/Makefile b/lib/Makefile
1139 index 50144a3aeebd..603630df298d 100644
1143 # Makefile for some libs needed in the kernel.
1146 +ifdef CONFIG_JFFS2_ZLIB
1147 + CONFIG_ZLIB_INFLATE:=y
1148 + CONFIG_ZLIB_DEFLATE:=y
1151 +ifdef CONFIG_JFFS2_LZMA
1152 + CONFIG_LZMA_DECOMPRESS:=y
1153 + CONFIG_LZMA_COMPRESS:=y
1156 ifdef CONFIG_FUNCTION_TRACER
1157 ORIG_CFLAGS := $(KBUILD_CFLAGS)
1158 KBUILD_CFLAGS = $(subst $(CC_FLAGS_FTRACE),,$(ORIG_CFLAGS))
1159 @@ -108,6 +118,8 @@ obj-$(CONFIG_LZ4HC_COMPRESS) += lz4/
1160 obj-$(CONFIG_LZ4_DECOMPRESS) += lz4/
1161 obj-$(CONFIG_XZ_DEC) += xz/
1162 obj-$(CONFIG_RAID6_PQ) += raid6/
1163 +obj-$(CONFIG_LZMA_COMPRESS) += lzma/
1164 +obj-$(CONFIG_LZMA_DECOMPRESS) += lzma/
1166 lib-$(CONFIG_DECOMPRESS_GZIP) += decompress_inflate.o
1167 lib-$(CONFIG_DECOMPRESS_BZIP2) += decompress_bunzip2.o
1168 diff --git a/lib/lzma/LzFind.c b/lib/lzma/LzFind.c
1169 new file mode 100644
1170 index 000000000000..e3ecb05420eb
1172 +++ b/lib/lzma/LzFind.c
1174 +/* LzFind.c -- Match finder for LZ algorithms
1175 +2009-04-22 : Igor Pavlov : Public domain */
1177 +#include <string.h>
1179 +#include "LzFind.h"
1180 +#include "LzHash.h"
1182 +#define kEmptyHashValue 0
1183 +#define kMaxValForNormalize ((UInt32)0xFFFFFFFF)
1184 +#define kNormalizeStepMin (1 << 10) /* it must be power of 2 */
1185 +#define kNormalizeMask (~(kNormalizeStepMin - 1))
1186 +#define kMaxHistorySize ((UInt32)3 << 30)
1188 +#define kStartMaxLen 3
1190 +static void LzInWindow_Free(CMatchFinder *p, ISzAlloc *alloc)
1192 + if (!p->directInput)
1194 + alloc->Free(alloc, p->bufferBase);
1195 + p->bufferBase = 0;
1199 +/* keepSizeBefore + keepSizeAfter + keepSizeReserv must be < 4G) */
1201 +static int LzInWindow_Create(CMatchFinder *p, UInt32 keepSizeReserv, ISzAlloc *alloc)
1203 + UInt32 blockSize = p->keepSizeBefore + p->keepSizeAfter + keepSizeReserv;
1204 + if (p->directInput)
1206 + p->blockSize = blockSize;
1209 + if (p->bufferBase == 0 || p->blockSize != blockSize)
1211 + LzInWindow_Free(p, alloc);
1212 + p->blockSize = blockSize;
1213 + p->bufferBase = (Byte *)alloc->Alloc(alloc, (size_t)blockSize);
1215 + return (p->bufferBase != 0);
1218 +Byte *MatchFinder_GetPointerToCurrentPos(CMatchFinder *p) { return p->buffer; }
1219 +Byte MatchFinder_GetIndexByte(CMatchFinder *p, Int32 index) { return p->buffer[index]; }
1221 +UInt32 MatchFinder_GetNumAvailableBytes(CMatchFinder *p) { return p->streamPos - p->pos; }
1223 +void MatchFinder_ReduceOffsets(CMatchFinder *p, UInt32 subValue)
1225 + p->posLimit -= subValue;
1226 + p->pos -= subValue;
1227 + p->streamPos -= subValue;
1230 +static void MatchFinder_ReadBlock(CMatchFinder *p)
1232 + if (p->streamEndWasReached || p->result != SZ_OK)
1234 + if (p->directInput)
1236 + UInt32 curSize = 0xFFFFFFFF - p->streamPos;
1237 + if (curSize > p->directInputRem)
1238 + curSize = (UInt32)p->directInputRem;
1239 + p->directInputRem -= curSize;
1240 + p->streamPos += curSize;
1241 + if (p->directInputRem == 0)
1242 + p->streamEndWasReached = 1;
1247 + Byte *dest = p->buffer + (p->streamPos - p->pos);
1248 + size_t size = (p->bufferBase + p->blockSize - dest);
1251 + p->result = p->stream->Read(p->stream, dest, &size);
1252 + if (p->result != SZ_OK)
1256 + p->streamEndWasReached = 1;
1259 + p->streamPos += (UInt32)size;
1260 + if (p->streamPos - p->pos > p->keepSizeAfter)
1265 +void MatchFinder_MoveBlock(CMatchFinder *p)
1267 + memmove(p->bufferBase,
1268 + p->buffer - p->keepSizeBefore,
1269 + (size_t)(p->streamPos - p->pos + p->keepSizeBefore));
1270 + p->buffer = p->bufferBase + p->keepSizeBefore;
1273 +int MatchFinder_NeedMove(CMatchFinder *p)
1275 + if (p->directInput)
1277 + /* if (p->streamEndWasReached) return 0; */
1278 + return ((size_t)(p->bufferBase + p->blockSize - p->buffer) <= p->keepSizeAfter);
1281 +void MatchFinder_ReadIfRequired(CMatchFinder *p)
1283 + if (p->streamEndWasReached)
1285 + if (p->keepSizeAfter >= p->streamPos - p->pos)
1286 + MatchFinder_ReadBlock(p);
1289 +static void MatchFinder_CheckAndMoveAndRead(CMatchFinder *p)
1291 + if (MatchFinder_NeedMove(p))
1292 + MatchFinder_MoveBlock(p);
1293 + MatchFinder_ReadBlock(p);
1296 +static void MatchFinder_SetDefaultSettings(CMatchFinder *p)
1300 + p->numHashBytes = 4;
1304 +#define kCrcPoly 0xEDB88320
1306 +void MatchFinder_Construct(CMatchFinder *p)
1309 + p->bufferBase = 0;
1310 + p->directInput = 0;
1312 + MatchFinder_SetDefaultSettings(p);
1314 + for (i = 0; i < 256; i++)
1318 + for (j = 0; j < 8; j++)
1319 + r = (r >> 1) ^ (kCrcPoly & ~((r & 1) - 1));
1324 +static void MatchFinder_FreeThisClassMemory(CMatchFinder *p, ISzAlloc *alloc)
1326 + alloc->Free(alloc, p->hash);
1330 +void MatchFinder_Free(CMatchFinder *p, ISzAlloc *alloc)
1332 + MatchFinder_FreeThisClassMemory(p, alloc);
1333 + LzInWindow_Free(p, alloc);
1336 +static CLzRef* AllocRefs(UInt32 num, ISzAlloc *alloc)
1338 + size_t sizeInBytes = (size_t)num * sizeof(CLzRef);
1339 + if (sizeInBytes / sizeof(CLzRef) != num)
1341 + return (CLzRef *)alloc->Alloc(alloc, sizeInBytes);
1344 +int MatchFinder_Create(CMatchFinder *p, UInt32 historySize,
1345 + UInt32 keepAddBufferBefore, UInt32 matchMaxLen, UInt32 keepAddBufferAfter,
1348 + UInt32 sizeReserv;
1349 + if (historySize > kMaxHistorySize)
1351 + MatchFinder_Free(p, alloc);
1354 + sizeReserv = historySize >> 1;
1355 + if (historySize > ((UInt32)2 << 30))
1356 + sizeReserv = historySize >> 2;
1357 + sizeReserv += (keepAddBufferBefore + matchMaxLen + keepAddBufferAfter) / 2 + (1 << 19);
1359 + p->keepSizeBefore = historySize + keepAddBufferBefore + 1;
1360 + p->keepSizeAfter = matchMaxLen + keepAddBufferAfter;
1361 + /* we need one additional byte, since we use MoveBlock after pos++ and before dictionary using */
1362 + if (LzInWindow_Create(p, sizeReserv, alloc))
1364 + UInt32 newCyclicBufferSize = historySize + 1;
1366 + p->matchMaxLen = matchMaxLen;
1368 + p->fixedHashSize = 0;
1369 + if (p->numHashBytes == 2)
1370 + hs = (1 << 16) - 1;
1373 + hs = historySize - 1;
1379 + hs |= 0xFFFF; /* don't change it! It's required for Deflate */
1380 + if (hs > (1 << 24))
1382 + if (p->numHashBytes == 3)
1383 + hs = (1 << 24) - 1;
1390 + if (p->numHashBytes > 2) p->fixedHashSize += kHash2Size;
1391 + if (p->numHashBytes > 3) p->fixedHashSize += kHash3Size;
1392 + if (p->numHashBytes > 4) p->fixedHashSize += kHash4Size;
1393 + hs += p->fixedHashSize;
1397 + UInt32 prevSize = p->hashSizeSum + p->numSons;
1399 + p->historySize = historySize;
1400 + p->hashSizeSum = hs;
1401 + p->cyclicBufferSize = newCyclicBufferSize;
1402 + p->numSons = (p->btMode ? newCyclicBufferSize * 2 : newCyclicBufferSize);
1403 + newSize = p->hashSizeSum + p->numSons;
1404 + if (p->hash != 0 && prevSize == newSize)
1406 + MatchFinder_FreeThisClassMemory(p, alloc);
1407 + p->hash = AllocRefs(newSize, alloc);
1410 + p->son = p->hash + p->hashSizeSum;
1415 + MatchFinder_Free(p, alloc);
1419 +static void MatchFinder_SetLimits(CMatchFinder *p)
1421 + UInt32 limit = kMaxValForNormalize - p->pos;
1422 + UInt32 limit2 = p->cyclicBufferSize - p->cyclicBufferPos;
1423 + if (limit2 < limit)
1425 + limit2 = p->streamPos - p->pos;
1426 + if (limit2 <= p->keepSizeAfter)
1432 + limit2 -= p->keepSizeAfter;
1433 + if (limit2 < limit)
1436 + UInt32 lenLimit = p->streamPos - p->pos;
1437 + if (lenLimit > p->matchMaxLen)
1438 + lenLimit = p->matchMaxLen;
1439 + p->lenLimit = lenLimit;
1441 + p->posLimit = p->pos + limit;
1444 +void MatchFinder_Init(CMatchFinder *p)
1447 + for (i = 0; i < p->hashSizeSum; i++)
1448 + p->hash[i] = kEmptyHashValue;
1449 + p->cyclicBufferPos = 0;
1450 + p->buffer = p->bufferBase;
1451 + p->pos = p->streamPos = p->cyclicBufferSize;
1452 + p->result = SZ_OK;
1453 + p->streamEndWasReached = 0;
1454 + MatchFinder_ReadBlock(p);
1455 + MatchFinder_SetLimits(p);
1458 +static UInt32 MatchFinder_GetSubValue(CMatchFinder *p)
1460 + return (p->pos - p->historySize - 1) & kNormalizeMask;
1463 +void MatchFinder_Normalize3(UInt32 subValue, CLzRef *items, UInt32 numItems)
1466 + for (i = 0; i < numItems; i++)
1468 + UInt32 value = items[i];
1469 + if (value <= subValue)
1470 + value = kEmptyHashValue;
1472 + value -= subValue;
1477 +static void MatchFinder_Normalize(CMatchFinder *p)
1479 + UInt32 subValue = MatchFinder_GetSubValue(p);
1480 + MatchFinder_Normalize3(subValue, p->hash, p->hashSizeSum + p->numSons);
1481 + MatchFinder_ReduceOffsets(p, subValue);
1484 +static void MatchFinder_CheckLimits(CMatchFinder *p)
1486 + if (p->pos == kMaxValForNormalize)
1487 + MatchFinder_Normalize(p);
1488 + if (!p->streamEndWasReached && p->keepSizeAfter == p->streamPos - p->pos)
1489 + MatchFinder_CheckAndMoveAndRead(p);
1490 + if (p->cyclicBufferPos == p->cyclicBufferSize)
1491 + p->cyclicBufferPos = 0;
1492 + MatchFinder_SetLimits(p);
1495 +static UInt32 * Hc_GetMatchesSpec(UInt32 lenLimit, UInt32 curMatch, UInt32 pos, const Byte *cur, CLzRef *son,
1496 + UInt32 _cyclicBufferPos, UInt32 _cyclicBufferSize, UInt32 cutValue,
1497 + UInt32 *distances, UInt32 maxLen)
1499 + son[_cyclicBufferPos] = curMatch;
1502 + UInt32 delta = pos - curMatch;
1503 + if (cutValue-- == 0 || delta >= _cyclicBufferSize)
1506 + const Byte *pb = cur - delta;
1507 + curMatch = son[_cyclicBufferPos - delta + ((delta > _cyclicBufferPos) ? _cyclicBufferSize : 0)];
1508 + if (pb[maxLen] == cur[maxLen] && *pb == *cur)
1511 + while (++len != lenLimit)
1512 + if (pb[len] != cur[len])
1516 + *distances++ = maxLen = len;
1517 + *distances++ = delta - 1;
1518 + if (len == lenLimit)
1526 +UInt32 * GetMatchesSpec1(UInt32 lenLimit, UInt32 curMatch, UInt32 pos, const Byte *cur, CLzRef *son,
1527 + UInt32 _cyclicBufferPos, UInt32 _cyclicBufferSize, UInt32 cutValue,
1528 + UInt32 *distances, UInt32 maxLen)
1530 + CLzRef *ptr0 = son + (_cyclicBufferPos << 1) + 1;
1531 + CLzRef *ptr1 = son + (_cyclicBufferPos << 1);
1532 + UInt32 len0 = 0, len1 = 0;
1535 + UInt32 delta = pos - curMatch;
1536 + if (cutValue-- == 0 || delta >= _cyclicBufferSize)
1538 + *ptr0 = *ptr1 = kEmptyHashValue;
1542 + CLzRef *pair = son + ((_cyclicBufferPos - delta + ((delta > _cyclicBufferPos) ? _cyclicBufferSize : 0)) << 1);
1543 + const Byte *pb = cur - delta;
1544 + UInt32 len = (len0 < len1 ? len0 : len1);
1545 + if (pb[len] == cur[len])
1547 + if (++len != lenLimit && pb[len] == cur[len])
1548 + while (++len != lenLimit)
1549 + if (pb[len] != cur[len])
1553 + *distances++ = maxLen = len;
1554 + *distances++ = delta - 1;
1555 + if (len == lenLimit)
1563 + if (pb[len] < cur[len])
1581 +static void SkipMatchesSpec(UInt32 lenLimit, UInt32 curMatch, UInt32 pos, const Byte *cur, CLzRef *son,
1582 + UInt32 _cyclicBufferPos, UInt32 _cyclicBufferSize, UInt32 cutValue)
1584 + CLzRef *ptr0 = son + (_cyclicBufferPos << 1) + 1;
1585 + CLzRef *ptr1 = son + (_cyclicBufferPos << 1);
1586 + UInt32 len0 = 0, len1 = 0;
1589 + UInt32 delta = pos - curMatch;
1590 + if (cutValue-- == 0 || delta >= _cyclicBufferSize)
1592 + *ptr0 = *ptr1 = kEmptyHashValue;
1596 + CLzRef *pair = son + ((_cyclicBufferPos - delta + ((delta > _cyclicBufferPos) ? _cyclicBufferSize : 0)) << 1);
1597 + const Byte *pb = cur - delta;
1598 + UInt32 len = (len0 < len1 ? len0 : len1);
1599 + if (pb[len] == cur[len])
1601 + while (++len != lenLimit)
1602 + if (pb[len] != cur[len])
1605 + if (len == lenLimit)
1613 + if (pb[len] < cur[len])
1632 + ++p->cyclicBufferPos; \
1634 + if (++p->pos == p->posLimit) MatchFinder_CheckLimits(p);
1636 +#define MOVE_POS_RET MOVE_POS return offset;
1638 +static void MatchFinder_MovePos(CMatchFinder *p) { MOVE_POS; }
1640 +#define GET_MATCHES_HEADER2(minLen, ret_op) \
1641 + UInt32 lenLimit; UInt32 hashValue; const Byte *cur; UInt32 curMatch; \
1642 + lenLimit = p->lenLimit; { if (lenLimit < minLen) { MatchFinder_MovePos(p); ret_op; }} \
1645 +#define GET_MATCHES_HEADER(minLen) GET_MATCHES_HEADER2(minLen, return 0)
1646 +#define SKIP_HEADER(minLen) GET_MATCHES_HEADER2(minLen, continue)
1648 +#define MF_PARAMS(p) p->pos, p->buffer, p->son, p->cyclicBufferPos, p->cyclicBufferSize, p->cutValue
1650 +#define GET_MATCHES_FOOTER(offset, maxLen) \
1651 + offset = (UInt32)(GetMatchesSpec1(lenLimit, curMatch, MF_PARAMS(p), \
1652 + distances + offset, maxLen) - distances); MOVE_POS_RET;
1654 +#define SKIP_FOOTER \
1655 + SkipMatchesSpec(lenLimit, curMatch, MF_PARAMS(p)); MOVE_POS;
1657 +static UInt32 Bt2_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances)
1660 + GET_MATCHES_HEADER(2)
1662 + curMatch = p->hash[hashValue];
1663 + p->hash[hashValue] = p->pos;
1665 + GET_MATCHES_FOOTER(offset, 1)
1668 +UInt32 Bt3Zip_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances)
1671 + GET_MATCHES_HEADER(3)
1673 + curMatch = p->hash[hashValue];
1674 + p->hash[hashValue] = p->pos;
1676 + GET_MATCHES_FOOTER(offset, 2)
1679 +static UInt32 Bt3_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances)
1681 + UInt32 hash2Value, delta2, maxLen, offset;
1682 + GET_MATCHES_HEADER(3)
1686 + delta2 = p->pos - p->hash[hash2Value];
1687 + curMatch = p->hash[kFix3HashSize + hashValue];
1689 + p->hash[hash2Value] =
1690 + p->hash[kFix3HashSize + hashValue] = p->pos;
1695 + if (delta2 < p->cyclicBufferSize && *(cur - delta2) == *cur)
1697 + for (; maxLen != lenLimit; maxLen++)
1698 + if (cur[(ptrdiff_t)maxLen - delta2] != cur[maxLen])
1700 + distances[0] = maxLen;
1701 + distances[1] = delta2 - 1;
1703 + if (maxLen == lenLimit)
1705 + SkipMatchesSpec(lenLimit, curMatch, MF_PARAMS(p));
1709 + GET_MATCHES_FOOTER(offset, maxLen)
1712 +static UInt32 Bt4_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances)
1714 + UInt32 hash2Value, hash3Value, delta2, delta3, maxLen, offset;
1715 + GET_MATCHES_HEADER(4)
1719 + delta2 = p->pos - p->hash[ hash2Value];
1720 + delta3 = p->pos - p->hash[kFix3HashSize + hash3Value];
1721 + curMatch = p->hash[kFix4HashSize + hashValue];
1723 + p->hash[ hash2Value] =
1724 + p->hash[kFix3HashSize + hash3Value] =
1725 + p->hash[kFix4HashSize + hashValue] = p->pos;
1729 + if (delta2 < p->cyclicBufferSize && *(cur - delta2) == *cur)
1731 + distances[0] = maxLen = 2;
1732 + distances[1] = delta2 - 1;
1735 + if (delta2 != delta3 && delta3 < p->cyclicBufferSize && *(cur - delta3) == *cur)
1738 + distances[offset + 1] = delta3 - 1;
1744 + for (; maxLen != lenLimit; maxLen++)
1745 + if (cur[(ptrdiff_t)maxLen - delta2] != cur[maxLen])
1747 + distances[offset - 2] = maxLen;
1748 + if (maxLen == lenLimit)
1750 + SkipMatchesSpec(lenLimit, curMatch, MF_PARAMS(p));
1756 + GET_MATCHES_FOOTER(offset, maxLen)
1759 +static UInt32 Hc4_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances)
1761 + UInt32 hash2Value, hash3Value, delta2, delta3, maxLen, offset;
1762 + GET_MATCHES_HEADER(4)
1766 + delta2 = p->pos - p->hash[ hash2Value];
1767 + delta3 = p->pos - p->hash[kFix3HashSize + hash3Value];
1768 + curMatch = p->hash[kFix4HashSize + hashValue];
1770 + p->hash[ hash2Value] =
1771 + p->hash[kFix3HashSize + hash3Value] =
1772 + p->hash[kFix4HashSize + hashValue] = p->pos;
1776 + if (delta2 < p->cyclicBufferSize && *(cur - delta2) == *cur)
1778 + distances[0] = maxLen = 2;
1779 + distances[1] = delta2 - 1;
1782 + if (delta2 != delta3 && delta3 < p->cyclicBufferSize && *(cur - delta3) == *cur)
1785 + distances[offset + 1] = delta3 - 1;
1791 + for (; maxLen != lenLimit; maxLen++)
1792 + if (cur[(ptrdiff_t)maxLen - delta2] != cur[maxLen])
1794 + distances[offset - 2] = maxLen;
1795 + if (maxLen == lenLimit)
1797 + p->son[p->cyclicBufferPos] = curMatch;
1803 + offset = (UInt32)(Hc_GetMatchesSpec(lenLimit, curMatch, MF_PARAMS(p),
1804 + distances + offset, maxLen) - (distances));
1808 +UInt32 Hc3Zip_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances)
1811 + GET_MATCHES_HEADER(3)
1813 + curMatch = p->hash[hashValue];
1814 + p->hash[hashValue] = p->pos;
1815 + offset = (UInt32)(Hc_GetMatchesSpec(lenLimit, curMatch, MF_PARAMS(p),
1816 + distances, 2) - (distances));
1820 +static void Bt2_MatchFinder_Skip(CMatchFinder *p, UInt32 num)
1826 + curMatch = p->hash[hashValue];
1827 + p->hash[hashValue] = p->pos;
1830 + while (--num != 0);
1833 +void Bt3Zip_MatchFinder_Skip(CMatchFinder *p, UInt32 num)
1839 + curMatch = p->hash[hashValue];
1840 + p->hash[hashValue] = p->pos;
1843 + while (--num != 0);
1846 +static void Bt3_MatchFinder_Skip(CMatchFinder *p, UInt32 num)
1850 + UInt32 hash2Value;
1853 + curMatch = p->hash[kFix3HashSize + hashValue];
1854 + p->hash[hash2Value] =
1855 + p->hash[kFix3HashSize + hashValue] = p->pos;
1858 + while (--num != 0);
1861 +static void Bt4_MatchFinder_Skip(CMatchFinder *p, UInt32 num)
1865 + UInt32 hash2Value, hash3Value;
1868 + curMatch = p->hash[kFix4HashSize + hashValue];
1869 + p->hash[ hash2Value] =
1870 + p->hash[kFix3HashSize + hash3Value] = p->pos;
1871 + p->hash[kFix4HashSize + hashValue] = p->pos;
1874 + while (--num != 0);
1877 +static void Hc4_MatchFinder_Skip(CMatchFinder *p, UInt32 num)
1881 + UInt32 hash2Value, hash3Value;
1884 + curMatch = p->hash[kFix4HashSize + hashValue];
1885 + p->hash[ hash2Value] =
1886 + p->hash[kFix3HashSize + hash3Value] =
1887 + p->hash[kFix4HashSize + hashValue] = p->pos;
1888 + p->son[p->cyclicBufferPos] = curMatch;
1891 + while (--num != 0);
1894 +void Hc3Zip_MatchFinder_Skip(CMatchFinder *p, UInt32 num)
1900 + curMatch = p->hash[hashValue];
1901 + p->hash[hashValue] = p->pos;
1902 + p->son[p->cyclicBufferPos] = curMatch;
1905 + while (--num != 0);
1908 +void MatchFinder_CreateVTable(CMatchFinder *p, IMatchFinder *vTable)
1910 + vTable->Init = (Mf_Init_Func)MatchFinder_Init;
1911 + vTable->GetIndexByte = (Mf_GetIndexByte_Func)MatchFinder_GetIndexByte;
1912 + vTable->GetNumAvailableBytes = (Mf_GetNumAvailableBytes_Func)MatchFinder_GetNumAvailableBytes;
1913 + vTable->GetPointerToCurrentPos = (Mf_GetPointerToCurrentPos_Func)MatchFinder_GetPointerToCurrentPos;
1916 + vTable->GetMatches = (Mf_GetMatches_Func)Hc4_MatchFinder_GetMatches;
1917 + vTable->Skip = (Mf_Skip_Func)Hc4_MatchFinder_Skip;
1919 + else if (p->numHashBytes == 2)
1921 + vTable->GetMatches = (Mf_GetMatches_Func)Bt2_MatchFinder_GetMatches;
1922 + vTable->Skip = (Mf_Skip_Func)Bt2_MatchFinder_Skip;
1924 + else if (p->numHashBytes == 3)
1926 + vTable->GetMatches = (Mf_GetMatches_Func)Bt3_MatchFinder_GetMatches;
1927 + vTable->Skip = (Mf_Skip_Func)Bt3_MatchFinder_Skip;
1931 + vTable->GetMatches = (Mf_GetMatches_Func)Bt4_MatchFinder_GetMatches;
1932 + vTable->Skip = (Mf_Skip_Func)Bt4_MatchFinder_Skip;
1935 diff --git a/lib/lzma/LzmaDec.c b/lib/lzma/LzmaDec.c
1936 new file mode 100644
1937 index 000000000000..2036761bf146
1939 +++ b/lib/lzma/LzmaDec.c
1941 +/* LzmaDec.c -- LZMA Decoder
1942 +2009-09-20 : Igor Pavlov : Public domain */
1944 +#include "LzmaDec.h"
1946 +#include <string.h>
1948 +#define kNumTopBits 24
1949 +#define kTopValue ((UInt32)1 << kNumTopBits)
1951 +#define kNumBitModelTotalBits 11
1952 +#define kBitModelTotal (1 << kNumBitModelTotalBits)
1953 +#define kNumMoveBits 5
1955 +#define RC_INIT_SIZE 5
1957 +#define NORMALIZE if (range < kTopValue) { range <<= 8; code = (code << 8) | (*buf++); }
1959 +#define IF_BIT_0(p) ttt = *(p); NORMALIZE; bound = (range >> kNumBitModelTotalBits) * ttt; if (code < bound)
1960 +#define UPDATE_0(p) range = bound; *(p) = (CLzmaProb)(ttt + ((kBitModelTotal - ttt) >> kNumMoveBits));
1961 +#define UPDATE_1(p) range -= bound; code -= bound; *(p) = (CLzmaProb)(ttt - (ttt >> kNumMoveBits));
1962 +#define GET_BIT2(p, i, A0, A1) IF_BIT_0(p) \
1963 + { UPDATE_0(p); i = (i + i); A0; } else \
1964 + { UPDATE_1(p); i = (i + i) + 1; A1; }
1965 +#define GET_BIT(p, i) GET_BIT2(p, i, ; , ;)
1967 +#define TREE_GET_BIT(probs, i) { GET_BIT((probs + i), i); }
1968 +#define TREE_DECODE(probs, limit, i) \
1969 + { i = 1; do { TREE_GET_BIT(probs, i); } while (i < limit); i -= limit; }
1971 +/* #define _LZMA_SIZE_OPT */
1973 +#ifdef _LZMA_SIZE_OPT
1974 +#define TREE_6_DECODE(probs, i) TREE_DECODE(probs, (1 << 6), i)
1976 +#define TREE_6_DECODE(probs, i) \
1978 + TREE_GET_BIT(probs, i); \
1979 + TREE_GET_BIT(probs, i); \
1980 + TREE_GET_BIT(probs, i); \
1981 + TREE_GET_BIT(probs, i); \
1982 + TREE_GET_BIT(probs, i); \
1983 + TREE_GET_BIT(probs, i); \
1987 +#define NORMALIZE_CHECK if (range < kTopValue) { if (buf >= bufLimit) return DUMMY_ERROR; range <<= 8; code = (code << 8) | (*buf++); }
1989 +#define IF_BIT_0_CHECK(p) ttt = *(p); NORMALIZE_CHECK; bound = (range >> kNumBitModelTotalBits) * ttt; if (code < bound)
1990 +#define UPDATE_0_CHECK range = bound;
1991 +#define UPDATE_1_CHECK range -= bound; code -= bound;
1992 +#define GET_BIT2_CHECK(p, i, A0, A1) IF_BIT_0_CHECK(p) \
1993 + { UPDATE_0_CHECK; i = (i + i); A0; } else \
1994 + { UPDATE_1_CHECK; i = (i + i) + 1; A1; }
1995 +#define GET_BIT_CHECK(p, i) GET_BIT2_CHECK(p, i, ; , ;)
1996 +#define TREE_DECODE_CHECK(probs, limit, i) \
1997 + { i = 1; do { GET_BIT_CHECK(probs + i, i) } while (i < limit); i -= limit; }
2000 +#define kNumPosBitsMax 4
2001 +#define kNumPosStatesMax (1 << kNumPosBitsMax)
2003 +#define kLenNumLowBits 3
2004 +#define kLenNumLowSymbols (1 << kLenNumLowBits)
2005 +#define kLenNumMidBits 3
2006 +#define kLenNumMidSymbols (1 << kLenNumMidBits)
2007 +#define kLenNumHighBits 8
2008 +#define kLenNumHighSymbols (1 << kLenNumHighBits)
2010 +#define LenChoice 0
2011 +#define LenChoice2 (LenChoice + 1)
2012 +#define LenLow (LenChoice2 + 1)
2013 +#define LenMid (LenLow + (kNumPosStatesMax << kLenNumLowBits))
2014 +#define LenHigh (LenMid + (kNumPosStatesMax << kLenNumMidBits))
2015 +#define kNumLenProbs (LenHigh + kLenNumHighSymbols)
2018 +#define kNumStates 12
2019 +#define kNumLitStates 7
2021 +#define kStartPosModelIndex 4
2022 +#define kEndPosModelIndex 14
2023 +#define kNumFullDistances (1 << (kEndPosModelIndex >> 1))
2025 +#define kNumPosSlotBits 6
2026 +#define kNumLenToPosStates 4
2028 +#define kNumAlignBits 4
2029 +#define kAlignTableSize (1 << kNumAlignBits)
2031 +#define kMatchMinLen 2
2032 +#define kMatchSpecLenStart (kMatchMinLen + kLenNumLowSymbols + kLenNumMidSymbols + kLenNumHighSymbols)
2035 +#define IsRep (IsMatch + (kNumStates << kNumPosBitsMax))
2036 +#define IsRepG0 (IsRep + kNumStates)
2037 +#define IsRepG1 (IsRepG0 + kNumStates)
2038 +#define IsRepG2 (IsRepG1 + kNumStates)
2039 +#define IsRep0Long (IsRepG2 + kNumStates)
2040 +#define PosSlot (IsRep0Long + (kNumStates << kNumPosBitsMax))
2041 +#define SpecPos (PosSlot + (kNumLenToPosStates << kNumPosSlotBits))
2042 +#define Align (SpecPos + kNumFullDistances - kEndPosModelIndex)
2043 +#define LenCoder (Align + kAlignTableSize)
2044 +#define RepLenCoder (LenCoder + kNumLenProbs)
2045 +#define Literal (RepLenCoder + kNumLenProbs)
2047 +#define LZMA_BASE_SIZE 1846
2048 +#define LZMA_LIT_SIZE 768
2050 +#define LzmaProps_GetNumProbs(p) ((UInt32)LZMA_BASE_SIZE + (LZMA_LIT_SIZE << ((p)->lc + (p)->lp)))
2052 +#if Literal != LZMA_BASE_SIZE
2053 +StopCompilingDueBUG
2056 +#define LZMA_DIC_MIN (1 << 12)
2058 +/* First LZMA-symbol is always decoded.
2059 +And it decodes new LZMA-symbols while (buf < bufLimit), but "buf" is without last normalization
2063 + SZ_ERROR_DATA - Error
2065 + < kMatchSpecLenStart : normal remain
2066 + = kMatchSpecLenStart : finished
2067 + = kMatchSpecLenStart + 1 : Flush marker
2068 + = kMatchSpecLenStart + 2 : State Init Marker
2071 +static int MY_FAST_CALL LzmaDec_DecodeReal(CLzmaDec *p, SizeT limit, const Byte *bufLimit)
2073 + CLzmaProb *probs = p->probs;
2075 + unsigned state = p->state;
2076 + UInt32 rep0 = p->reps[0], rep1 = p->reps[1], rep2 = p->reps[2], rep3 = p->reps[3];
2077 + unsigned pbMask = ((unsigned)1 << (p->prop.pb)) - 1;
2078 + unsigned lpMask = ((unsigned)1 << (p->prop.lp)) - 1;
2079 + unsigned lc = p->prop.lc;
2081 + Byte *dic = p->dic;
2082 + SizeT dicBufSize = p->dicBufSize;
2083 + SizeT dicPos = p->dicPos;
2085 + UInt32 processedPos = p->processedPos;
2086 + UInt32 checkDicSize = p->checkDicSize;
2089 + const Byte *buf = p->buf;
2090 + UInt32 range = p->range;
2091 + UInt32 code = p->code;
2098 + unsigned posState = processedPos & pbMask;
2100 + prob = probs + IsMatch + (state << kNumPosBitsMax) + posState;
2105 + prob = probs + Literal;
2106 + if (checkDicSize != 0 || processedPos != 0)
2107 + prob += (LZMA_LIT_SIZE * (((processedPos & lpMask) << lc) +
2108 + (dic[(dicPos == 0 ? dicBufSize : dicPos) - 1] >> (8 - lc))));
2110 + if (state < kNumLitStates)
2112 + state -= (state < 4) ? state : 3;
2114 + do { GET_BIT(prob + symbol, symbol) } while (symbol < 0x100);
2118 + unsigned matchByte = p->dic[(dicPos - rep0) + ((dicPos < rep0) ? dicBufSize : 0)];
2119 + unsigned offs = 0x100;
2120 + state -= (state < 10) ? 3 : 6;
2125 + CLzmaProb *probLit;
2127 + bit = (matchByte & offs);
2128 + probLit = prob + offs + bit + symbol;
2129 + GET_BIT2(probLit, symbol, offs &= ~bit, offs &= bit)
2131 + while (symbol < 0x100);
2133 + dic[dicPos++] = (Byte)symbol;
2140 + prob = probs + IsRep + state;
2144 + state += kNumStates;
2145 + prob = probs + LenCoder;
2150 + if (checkDicSize == 0 && processedPos == 0)
2151 + return SZ_ERROR_DATA;
2152 + prob = probs + IsRepG0 + state;
2156 + prob = probs + IsRep0Long + (state << kNumPosBitsMax) + posState;
2160 + dic[dicPos] = dic[(dicPos - rep0) + ((dicPos < rep0) ? dicBufSize : 0)];
2163 + state = state < kNumLitStates ? 9 : 11;
2172 + prob = probs + IsRepG1 + state;
2181 + prob = probs + IsRepG2 + state;
2198 + state = state < kNumLitStates ? 8 : 11;
2199 + prob = probs + RepLenCoder;
2202 + unsigned limit, offset;
2203 + CLzmaProb *probLen = prob + LenChoice;
2206 + UPDATE_0(probLen);
2207 + probLen = prob + LenLow + (posState << kLenNumLowBits);
2209 + limit = (1 << kLenNumLowBits);
2213 + UPDATE_1(probLen);
2214 + probLen = prob + LenChoice2;
2217 + UPDATE_0(probLen);
2218 + probLen = prob + LenMid + (posState << kLenNumMidBits);
2219 + offset = kLenNumLowSymbols;
2220 + limit = (1 << kLenNumMidBits);
2224 + UPDATE_1(probLen);
2225 + probLen = prob + LenHigh;
2226 + offset = kLenNumLowSymbols + kLenNumMidSymbols;
2227 + limit = (1 << kLenNumHighBits);
2230 + TREE_DECODE(probLen, limit, len);
2234 + if (state >= kNumStates)
2237 + prob = probs + PosSlot +
2238 + ((len < kNumLenToPosStates ? len : kNumLenToPosStates - 1) << kNumPosSlotBits);
2239 + TREE_6_DECODE(prob, distance);
2240 + if (distance >= kStartPosModelIndex)
2242 + unsigned posSlot = (unsigned)distance;
2243 + int numDirectBits = (int)(((distance >> 1) - 1));
2244 + distance = (2 | (distance & 1));
2245 + if (posSlot < kEndPosModelIndex)
2247 + distance <<= numDirectBits;
2248 + prob = probs + SpecPos + distance - posSlot - 1;
2254 + GET_BIT2(prob + i, i, ; , distance |= mask);
2257 + while (--numDirectBits != 0);
2262 + numDirectBits -= kNumAlignBits;
2271 + t = (0 - ((UInt32)code >> 31)); /* (UInt32)((Int32)code >> 31) */
2272 + distance = (distance << 1) + (t + 1);
2273 + code += range & t;
2277 + if (code >= range)
2284 + while (--numDirectBits != 0);
2285 + prob = probs + Align;
2286 + distance <<= kNumAlignBits;
2289 + GET_BIT2(prob + i, i, ; , distance |= 1);
2290 + GET_BIT2(prob + i, i, ; , distance |= 2);
2291 + GET_BIT2(prob + i, i, ; , distance |= 4);
2292 + GET_BIT2(prob + i, i, ; , distance |= 8);
2294 + if (distance == (UInt32)0xFFFFFFFF)
2296 + len += kMatchSpecLenStart;
2297 + state -= kNumStates;
2305 + rep0 = distance + 1;
2306 + if (checkDicSize == 0)
2308 + if (distance >= processedPos)
2309 + return SZ_ERROR_DATA;
2311 + else if (distance >= checkDicSize)
2312 + return SZ_ERROR_DATA;
2313 + state = (state < kNumStates + kNumLitStates) ? kNumLitStates : kNumLitStates + 3;
2316 + len += kMatchMinLen;
2318 + if (limit == dicPos)
2319 + return SZ_ERROR_DATA;
2321 + SizeT rem = limit - dicPos;
2322 + unsigned curLen = ((rem < len) ? (unsigned)rem : len);
2323 + SizeT pos = (dicPos - rep0) + ((dicPos < rep0) ? dicBufSize : 0);
2325 + processedPos += curLen;
2328 + if (pos + curLen <= dicBufSize)
2330 + Byte *dest = dic + dicPos;
2331 + ptrdiff_t src = (ptrdiff_t)pos - (ptrdiff_t)dicPos;
2332 + const Byte *lim = dest + curLen;
2335 + *(dest) = (Byte)*(dest + src);
2336 + while (++dest != lim);
2342 + dic[dicPos++] = dic[pos];
2343 + if (++pos == dicBufSize)
2346 + while (--curLen != 0);
2351 + while (dicPos < limit && buf < bufLimit);
2356 + p->remainLen = len;
2357 + p->dicPos = dicPos;
2358 + p->processedPos = processedPos;
2359 + p->reps[0] = rep0;
2360 + p->reps[1] = rep1;
2361 + p->reps[2] = rep2;
2362 + p->reps[3] = rep3;
2368 +static void MY_FAST_CALL LzmaDec_WriteRem(CLzmaDec *p, SizeT limit)
2370 + if (p->remainLen != 0 && p->remainLen < kMatchSpecLenStart)
2372 + Byte *dic = p->dic;
2373 + SizeT dicPos = p->dicPos;
2374 + SizeT dicBufSize = p->dicBufSize;
2375 + unsigned len = p->remainLen;
2376 + UInt32 rep0 = p->reps[0];
2377 + if (limit - dicPos < len)
2378 + len = (unsigned)(limit - dicPos);
2380 + if (p->checkDicSize == 0 && p->prop.dicSize - p->processedPos <= len)
2381 + p->checkDicSize = p->prop.dicSize;
2383 + p->processedPos += len;
2384 + p->remainLen -= len;
2385 + while (len-- != 0)
2387 + dic[dicPos] = dic[(dicPos - rep0) + ((dicPos < rep0) ? dicBufSize : 0)];
2390 + p->dicPos = dicPos;
2394 +static int MY_FAST_CALL LzmaDec_DecodeReal2(CLzmaDec *p, SizeT limit, const Byte *bufLimit)
2398 + SizeT limit2 = limit;
2399 + if (p->checkDicSize == 0)
2401 + UInt32 rem = p->prop.dicSize - p->processedPos;
2402 + if (limit - p->dicPos > rem)
2403 + limit2 = p->dicPos + rem;
2405 + RINOK(LzmaDec_DecodeReal(p, limit2, bufLimit));
2406 + if (p->processedPos >= p->prop.dicSize)
2407 + p->checkDicSize = p->prop.dicSize;
2408 + LzmaDec_WriteRem(p, limit);
2410 + while (p->dicPos < limit && p->buf < bufLimit && p->remainLen < kMatchSpecLenStart);
2412 + if (p->remainLen > kMatchSpecLenStart)
2414 + p->remainLen = kMatchSpecLenStart;
2421 + DUMMY_ERROR, /* unexpected end of input stream */
2427 +static ELzmaDummy LzmaDec_TryDummy(const CLzmaDec *p, const Byte *buf, SizeT inSize)
2429 + UInt32 range = p->range;
2430 + UInt32 code = p->code;
2431 + const Byte *bufLimit = buf + inSize;
2432 + CLzmaProb *probs = p->probs;
2433 + unsigned state = p->state;
2440 + unsigned posState = (p->processedPos) & ((1 << p->prop.pb) - 1);
2442 + prob = probs + IsMatch + (state << kNumPosBitsMax) + posState;
2443 + IF_BIT_0_CHECK(prob)
2447 + /* if (bufLimit - buf >= 7) return DUMMY_LIT; */
2449 + prob = probs + Literal;
2450 + if (p->checkDicSize != 0 || p->processedPos != 0)
2451 + prob += (LZMA_LIT_SIZE *
2452 + ((((p->processedPos) & ((1 << (p->prop.lp)) - 1)) << p->prop.lc) +
2453 + (p->dic[(p->dicPos == 0 ? p->dicBufSize : p->dicPos) - 1] >> (8 - p->prop.lc))));
2455 + if (state < kNumLitStates)
2457 + unsigned symbol = 1;
2458 + do { GET_BIT_CHECK(prob + symbol, symbol) } while (symbol < 0x100);
2462 + unsigned matchByte = p->dic[p->dicPos - p->reps[0] +
2463 + ((p->dicPos < p->reps[0]) ? p->dicBufSize : 0)];
2464 + unsigned offs = 0x100;
2465 + unsigned symbol = 1;
2469 + CLzmaProb *probLit;
2471 + bit = (matchByte & offs);
2472 + probLit = prob + offs + bit + symbol;
2473 + GET_BIT2_CHECK(probLit, symbol, offs &= ~bit, offs &= bit)
2475 + while (symbol < 0x100);
2484 + prob = probs + IsRep + state;
2485 + IF_BIT_0_CHECK(prob)
2489 + prob = probs + LenCoder;
2490 + res = DUMMY_MATCH;
2496 + prob = probs + IsRepG0 + state;
2497 + IF_BIT_0_CHECK(prob)
2500 + prob = probs + IsRep0Long + (state << kNumPosBitsMax) + posState;
2501 + IF_BIT_0_CHECK(prob)
2515 + prob = probs + IsRepG1 + state;
2516 + IF_BIT_0_CHECK(prob)
2523 + prob = probs + IsRepG2 + state;
2524 + IF_BIT_0_CHECK(prob)
2534 + state = kNumStates;
2535 + prob = probs + RepLenCoder;
2538 + unsigned limit, offset;
2539 + CLzmaProb *probLen = prob + LenChoice;
2540 + IF_BIT_0_CHECK(probLen)
2543 + probLen = prob + LenLow + (posState << kLenNumLowBits);
2545 + limit = 1 << kLenNumLowBits;
2550 + probLen = prob + LenChoice2;
2551 + IF_BIT_0_CHECK(probLen)
2554 + probLen = prob + LenMid + (posState << kLenNumMidBits);
2555 + offset = kLenNumLowSymbols;
2556 + limit = 1 << kLenNumMidBits;
2561 + probLen = prob + LenHigh;
2562 + offset = kLenNumLowSymbols + kLenNumMidSymbols;
2563 + limit = 1 << kLenNumHighBits;
2566 + TREE_DECODE_CHECK(probLen, limit, len);
2573 + prob = probs + PosSlot +
2574 + ((len < kNumLenToPosStates ? len : kNumLenToPosStates - 1) <<
2576 + TREE_DECODE_CHECK(prob, 1 << kNumPosSlotBits, posSlot);
2577 + if (posSlot >= kStartPosModelIndex)
2579 + int numDirectBits = ((posSlot >> 1) - 1);
2581 + /* if (bufLimit - buf >= 8) return DUMMY_MATCH; */
2583 + if (posSlot < kEndPosModelIndex)
2585 + prob = probs + SpecPos + ((2 | (posSlot & 1)) << numDirectBits) - posSlot - 1;
2589 + numDirectBits -= kNumAlignBits;
2594 + code -= range & (((code - range) >> 31) - 1);
2595 + /* if (code >= range) code -= range; */
2597 + while (--numDirectBits != 0);
2598 + prob = probs + Align;
2599 + numDirectBits = kNumAlignBits;
2605 + GET_BIT_CHECK(prob + i, i);
2607 + while (--numDirectBits != 0);
2618 +static void LzmaDec_InitRc(CLzmaDec *p, const Byte *data)
2620 + p->code = ((UInt32)data[1] << 24) | ((UInt32)data[2] << 16) | ((UInt32)data[3] << 8) | ((UInt32)data[4]);
2621 + p->range = 0xFFFFFFFF;
2625 +void LzmaDec_InitDicAndState(CLzmaDec *p, Bool initDic, Bool initState)
2629 + p->tempBufSize = 0;
2633 + p->processedPos = 0;
2634 + p->checkDicSize = 0;
2635 + p->needInitState = 1;
2638 + p->needInitState = 1;
2641 +void LzmaDec_Init(CLzmaDec *p)
2644 + LzmaDec_InitDicAndState(p, True, True);
2647 +static void LzmaDec_InitStateReal(CLzmaDec *p)
2649 + UInt32 numProbs = Literal + ((UInt32)LZMA_LIT_SIZE << (p->prop.lc + p->prop.lp));
2651 + CLzmaProb *probs = p->probs;
2652 + for (i = 0; i < numProbs; i++)
2653 + probs[i] = kBitModelTotal >> 1;
2654 + p->reps[0] = p->reps[1] = p->reps[2] = p->reps[3] = 1;
2656 + p->needInitState = 0;
2659 +SRes LzmaDec_DecodeToDic(CLzmaDec *p, SizeT dicLimit, const Byte *src, SizeT *srcLen,
2660 + ELzmaFinishMode finishMode, ELzmaStatus *status)
2662 + SizeT inSize = *srcLen;
2664 + LzmaDec_WriteRem(p, dicLimit);
2666 + *status = LZMA_STATUS_NOT_SPECIFIED;
2668 + while (p->remainLen != kMatchSpecLenStart)
2670 + int checkEndMarkNow;
2672 + if (p->needFlush != 0)
2674 + for (; inSize > 0 && p->tempBufSize < RC_INIT_SIZE; (*srcLen)++, inSize--)
2675 + p->tempBuf[p->tempBufSize++] = *src++;
2676 + if (p->tempBufSize < RC_INIT_SIZE)
2678 + *status = LZMA_STATUS_NEEDS_MORE_INPUT;
2681 + if (p->tempBuf[0] != 0)
2682 + return SZ_ERROR_DATA;
2684 + LzmaDec_InitRc(p, p->tempBuf);
2685 + p->tempBufSize = 0;
2688 + checkEndMarkNow = 0;
2689 + if (p->dicPos >= dicLimit)
2691 + if (p->remainLen == 0 && p->code == 0)
2693 + *status = LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK;
2696 + if (finishMode == LZMA_FINISH_ANY)
2698 + *status = LZMA_STATUS_NOT_FINISHED;
2701 + if (p->remainLen != 0)
2703 + *status = LZMA_STATUS_NOT_FINISHED;
2704 + return SZ_ERROR_DATA;
2706 + checkEndMarkNow = 1;
2709 + if (p->needInitState)
2710 + LzmaDec_InitStateReal(p);
2712 + if (p->tempBufSize == 0)
2715 + const Byte *bufLimit;
2716 + if (inSize < LZMA_REQUIRED_INPUT_MAX || checkEndMarkNow)
2718 + int dummyRes = LzmaDec_TryDummy(p, src, inSize);
2719 + if (dummyRes == DUMMY_ERROR)
2721 + memcpy(p->tempBuf, src, inSize);
2722 + p->tempBufSize = (unsigned)inSize;
2723 + (*srcLen) += inSize;
2724 + *status = LZMA_STATUS_NEEDS_MORE_INPUT;
2727 + if (checkEndMarkNow && dummyRes != DUMMY_MATCH)
2729 + *status = LZMA_STATUS_NOT_FINISHED;
2730 + return SZ_ERROR_DATA;
2735 + bufLimit = src + inSize - LZMA_REQUIRED_INPUT_MAX;
2737 + if (LzmaDec_DecodeReal2(p, dicLimit, bufLimit) != 0)
2738 + return SZ_ERROR_DATA;
2739 + processed = (SizeT)(p->buf - src);
2740 + (*srcLen) += processed;
2742 + inSize -= processed;
2746 + unsigned rem = p->tempBufSize, lookAhead = 0;
2747 + while (rem < LZMA_REQUIRED_INPUT_MAX && lookAhead < inSize)
2748 + p->tempBuf[rem++] = src[lookAhead++];
2749 + p->tempBufSize = rem;
2750 + if (rem < LZMA_REQUIRED_INPUT_MAX || checkEndMarkNow)
2752 + int dummyRes = LzmaDec_TryDummy(p, p->tempBuf, rem);
2753 + if (dummyRes == DUMMY_ERROR)
2755 + (*srcLen) += lookAhead;
2756 + *status = LZMA_STATUS_NEEDS_MORE_INPUT;
2759 + if (checkEndMarkNow && dummyRes != DUMMY_MATCH)
2761 + *status = LZMA_STATUS_NOT_FINISHED;
2762 + return SZ_ERROR_DATA;
2765 + p->buf = p->tempBuf;
2766 + if (LzmaDec_DecodeReal2(p, dicLimit, p->buf) != 0)
2767 + return SZ_ERROR_DATA;
2768 + lookAhead -= (rem - (unsigned)(p->buf - p->tempBuf));
2769 + (*srcLen) += lookAhead;
2771 + inSize -= lookAhead;
2772 + p->tempBufSize = 0;
2776 + *status = LZMA_STATUS_FINISHED_WITH_MARK;
2777 + return (p->code == 0) ? SZ_OK : SZ_ERROR_DATA;
2780 +SRes LzmaDec_DecodeToBuf(CLzmaDec *p, Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen, ELzmaFinishMode finishMode, ELzmaStatus *status)
2782 + SizeT outSize = *destLen;
2783 + SizeT inSize = *srcLen;
2784 + *srcLen = *destLen = 0;
2787 + SizeT inSizeCur = inSize, outSizeCur, dicPos;
2788 + ELzmaFinishMode curFinishMode;
2790 + if (p->dicPos == p->dicBufSize)
2792 + dicPos = p->dicPos;
2793 + if (outSize > p->dicBufSize - dicPos)
2795 + outSizeCur = p->dicBufSize;
2796 + curFinishMode = LZMA_FINISH_ANY;
2800 + outSizeCur = dicPos + outSize;
2801 + curFinishMode = finishMode;
2804 + res = LzmaDec_DecodeToDic(p, outSizeCur, src, &inSizeCur, curFinishMode, status);
2806 + inSize -= inSizeCur;
2807 + *srcLen += inSizeCur;
2808 + outSizeCur = p->dicPos - dicPos;
2809 + memcpy(dest, p->dic + dicPos, outSizeCur);
2810 + dest += outSizeCur;
2811 + outSize -= outSizeCur;
2812 + *destLen += outSizeCur;
2815 + if (outSizeCur == 0 || outSize == 0)
2820 +void LzmaDec_FreeProbs(CLzmaDec *p, ISzAlloc *alloc)
2822 + alloc->Free(alloc, p->probs);
2826 +static void LzmaDec_FreeDict(CLzmaDec *p, ISzAlloc *alloc)
2828 + alloc->Free(alloc, p->dic);
2832 +void LzmaDec_Free(CLzmaDec *p, ISzAlloc *alloc)
2834 + LzmaDec_FreeProbs(p, alloc);
2835 + LzmaDec_FreeDict(p, alloc);
2838 +SRes LzmaProps_Decode(CLzmaProps *p, const Byte *data, unsigned size)
2843 + if (size < LZMA_PROPS_SIZE)
2844 + return SZ_ERROR_UNSUPPORTED;
2846 + dicSize = data[1] | ((UInt32)data[2] << 8) | ((UInt32)data[3] << 16) | ((UInt32)data[4] << 24);
2848 + if (dicSize < LZMA_DIC_MIN)
2849 + dicSize = LZMA_DIC_MIN;
2850 + p->dicSize = dicSize;
2853 + if (d >= (9 * 5 * 5))
2854 + return SZ_ERROR_UNSUPPORTED;
2864 +static SRes LzmaDec_AllocateProbs2(CLzmaDec *p, const CLzmaProps *propNew, ISzAlloc *alloc)
2866 + UInt32 numProbs = LzmaProps_GetNumProbs(propNew);
2867 + if (p->probs == 0 || numProbs != p->numProbs)
2869 + LzmaDec_FreeProbs(p, alloc);
2870 + p->probs = (CLzmaProb *)alloc->Alloc(alloc, numProbs * sizeof(CLzmaProb));
2871 + p->numProbs = numProbs;
2872 + if (p->probs == 0)
2873 + return SZ_ERROR_MEM;
2878 +SRes LzmaDec_AllocateProbs(CLzmaDec *p, const Byte *props, unsigned propsSize, ISzAlloc *alloc)
2880 + CLzmaProps propNew;
2881 + RINOK(LzmaProps_Decode(&propNew, props, propsSize));
2882 + RINOK(LzmaDec_AllocateProbs2(p, &propNew, alloc));
2883 + p->prop = propNew;
2887 +SRes LzmaDec_Allocate(CLzmaDec *p, const Byte *props, unsigned propsSize, ISzAlloc *alloc)
2889 + CLzmaProps propNew;
2891 + RINOK(LzmaProps_Decode(&propNew, props, propsSize));
2892 + RINOK(LzmaDec_AllocateProbs2(p, &propNew, alloc));
2893 + dicBufSize = propNew.dicSize;
2894 + if (p->dic == 0 || dicBufSize != p->dicBufSize)
2896 + LzmaDec_FreeDict(p, alloc);
2897 + p->dic = (Byte *)alloc->Alloc(alloc, dicBufSize);
2900 + LzmaDec_FreeProbs(p, alloc);
2901 + return SZ_ERROR_MEM;
2904 + p->dicBufSize = dicBufSize;
2905 + p->prop = propNew;
2909 +SRes LzmaDecode(Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen,
2910 + const Byte *propData, unsigned propSize, ELzmaFinishMode finishMode,
2911 + ELzmaStatus *status, ISzAlloc *alloc)
2915 + SizeT inSize = *srcLen;
2916 + SizeT outSize = *destLen;
2917 + *srcLen = *destLen = 0;
2918 + if (inSize < RC_INIT_SIZE)
2919 + return SZ_ERROR_INPUT_EOF;
2921 + LzmaDec_Construct(&p);
2922 + res = LzmaDec_AllocateProbs(&p, propData, propSize, alloc);
2926 + p.dicBufSize = outSize;
2931 + res = LzmaDec_DecodeToDic(&p, outSize, src, srcLen, finishMode, status);
2933 + if (res == SZ_OK && *status == LZMA_STATUS_NEEDS_MORE_INPUT)
2934 + res = SZ_ERROR_INPUT_EOF;
2936 + (*destLen) = p.dicPos;
2937 + LzmaDec_FreeProbs(&p, alloc);
2940 diff --git a/lib/lzma/LzmaEnc.c b/lib/lzma/LzmaEnc.c
2941 new file mode 100644
2942 index 000000000000..6dadf00dfab2
2944 +++ b/lib/lzma/LzmaEnc.c
2946 +/* LzmaEnc.c -- LZMA Encoder
2947 +2009-11-24 : Igor Pavlov : Public domain */
2949 +#include <string.h>
2951 +/* #define SHOW_STAT */
2952 +/* #define SHOW_STAT2 */
2954 +#if defined(SHOW_STAT) || defined(SHOW_STAT2)
2958 +#include "LzmaEnc.h"
2963 +#include "LzFind.h"
2965 +#include "LzFindMt.h"
2969 +static int ttt = 0;
2972 +#define kBlockSizeMax ((1 << LZMA_NUM_BLOCK_SIZE_BITS) - 1)
2974 +#define kBlockSize (9 << 10)
2975 +#define kUnpackBlockSize (1 << 18)
2976 +#define kMatchArraySize (1 << 21)
2977 +#define kMatchRecordMaxSize ((LZMA_MATCH_LEN_MAX * 2 + 3) * LZMA_MATCH_LEN_MAX)
2979 +#define kNumMaxDirectBits (31)
2981 +#define kNumTopBits 24
2982 +#define kTopValue ((UInt32)1 << kNumTopBits)
2984 +#define kNumBitModelTotalBits 11
2985 +#define kBitModelTotal (1 << kNumBitModelTotalBits)
2986 +#define kNumMoveBits 5
2987 +#define kProbInitValue (kBitModelTotal >> 1)
2989 +#define kNumMoveReducingBits 4
2990 +#define kNumBitPriceShiftBits 4
2991 +#define kBitPrice (1 << kNumBitPriceShiftBits)
2993 +void LzmaEncProps_Init(CLzmaEncProps *p)
2996 + p->dictSize = p->mc = 0;
2997 + p->lc = p->lp = p->pb = p->algo = p->fb = p->btMode = p->numHashBytes = p->numThreads = -1;
2998 + p->writeEndMark = 0;
3001 +void LzmaEncProps_Normalize(CLzmaEncProps *p)
3003 + int level = p->level;
3004 + if (level < 0) level = 5;
3006 + if (p->dictSize == 0) p->dictSize = (level <= 5 ? (1 << (level * 2 + 14)) : (level == 6 ? (1 << 25) : (1 << 26)));
3007 + if (p->lc < 0) p->lc = 3;
3008 + if (p->lp < 0) p->lp = 0;
3009 + if (p->pb < 0) p->pb = 2;
3010 + if (p->algo < 0) p->algo = (level < 5 ? 0 : 1);
3011 + if (p->fb < 0) p->fb = (level < 7 ? 32 : 64);
3012 + if (p->btMode < 0) p->btMode = (p->algo == 0 ? 0 : 1);
3013 + if (p->numHashBytes < 0) p->numHashBytes = 4;
3014 + if (p->mc == 0) p->mc = (16 + (p->fb >> 1)) >> (p->btMode ? 0 : 1);
3015 + if (p->numThreads < 0)
3018 + ((p->btMode && p->algo) ? 2 : 1);
3024 +UInt32 LzmaEncProps_GetDictSize(const CLzmaEncProps *props2)
3026 + CLzmaEncProps props = *props2;
3027 + LzmaEncProps_Normalize(&props);
3028 + return props.dictSize;
3031 +/* #define LZMA_LOG_BSR */
3032 +/* Define it for Intel's CPU */
3035 +#ifdef LZMA_LOG_BSR
3037 +#define kDicLogSizeMaxCompress 30
3039 +#define BSR2_RET(pos, res) { unsigned long i; _BitScanReverse(&i, (pos)); res = (i + i) + ((pos >> (i - 1)) & 1); }
3041 +UInt32 GetPosSlot1(UInt32 pos)
3044 + BSR2_RET(pos, res);
3047 +#define GetPosSlot2(pos, res) { BSR2_RET(pos, res); }
3048 +#define GetPosSlot(pos, res) { if (pos < 2) res = pos; else BSR2_RET(pos, res); }
3052 +#define kNumLogBits (9 + (int)sizeof(size_t) / 2)
3053 +#define kDicLogSizeMaxCompress ((kNumLogBits - 1) * 2 + 7)
3055 +void LzmaEnc_FastPosInit(Byte *g_FastPos)
3057 + int c = 2, slotFast;
3061 + for (slotFast = 2; slotFast < kNumLogBits * 2; slotFast++)
3063 + UInt32 k = (1 << ((slotFast >> 1) - 1));
3065 + for (j = 0; j < k; j++, c++)
3066 + g_FastPos[c] = (Byte)slotFast;
3070 +#define BSR2_RET(pos, res) { UInt32 i = 6 + ((kNumLogBits - 1) & \
3071 + (0 - (((((UInt32)1 << (kNumLogBits + 6)) - 1) - pos) >> 31))); \
3072 + res = p->g_FastPos[pos >> i] + (i * 2); }
3074 +#define BSR2_RET(pos, res) { res = (pos < (1 << (kNumLogBits + 6))) ? \
3075 + p->g_FastPos[pos >> 6] + 12 : \
3076 + p->g_FastPos[pos >> (6 + kNumLogBits - 1)] + (6 + (kNumLogBits - 1)) * 2; }
3079 +#define GetPosSlot1(pos) p->g_FastPos[pos]
3080 +#define GetPosSlot2(pos, res) { BSR2_RET(pos, res); }
3081 +#define GetPosSlot(pos, res) { if (pos < kNumFullDistances) res = p->g_FastPos[pos]; else BSR2_RET(pos, res); }
3086 +#define LZMA_NUM_REPS 4
3088 +typedef unsigned CState;
3103 + UInt32 backs[LZMA_NUM_REPS];
3106 +#define kNumOpts (1 << 12)
3108 +#define kNumLenToPosStates 4
3109 +#define kNumPosSlotBits 6
3110 +#define kDicLogSizeMin 0
3111 +#define kDicLogSizeMax 32
3112 +#define kDistTableSizeMax (kDicLogSizeMax * 2)
3115 +#define kNumAlignBits 4
3116 +#define kAlignTableSize (1 << kNumAlignBits)
3117 +#define kAlignMask (kAlignTableSize - 1)
3119 +#define kStartPosModelIndex 4
3120 +#define kEndPosModelIndex 14
3121 +#define kNumPosModels (kEndPosModelIndex - kStartPosModelIndex)
3123 +#define kNumFullDistances (1 << (kEndPosModelIndex >> 1))
3125 +#ifdef _LZMA_PROB32
3126 +#define CLzmaProb UInt32
3128 +#define CLzmaProb UInt16
3131 +#define LZMA_PB_MAX 4
3132 +#define LZMA_LC_MAX 8
3133 +#define LZMA_LP_MAX 4
3135 +#define LZMA_NUM_PB_STATES_MAX (1 << LZMA_PB_MAX)
3138 +#define kLenNumLowBits 3
3139 +#define kLenNumLowSymbols (1 << kLenNumLowBits)
3140 +#define kLenNumMidBits 3
3141 +#define kLenNumMidSymbols (1 << kLenNumMidBits)
3142 +#define kLenNumHighBits 8
3143 +#define kLenNumHighSymbols (1 << kLenNumHighBits)
3145 +#define kLenNumSymbolsTotal (kLenNumLowSymbols + kLenNumMidSymbols + kLenNumHighSymbols)
3147 +#define LZMA_MATCH_LEN_MIN 2
3148 +#define LZMA_MATCH_LEN_MAX (LZMA_MATCH_LEN_MIN + kLenNumSymbolsTotal - 1)
3150 +#define kNumStates 12
3155 + CLzmaProb choice2;
3156 + CLzmaProb low[LZMA_NUM_PB_STATES_MAX << kLenNumLowBits];
3157 + CLzmaProb mid[LZMA_NUM_PB_STATES_MAX << kLenNumMidBits];
3158 + CLzmaProb high[kLenNumHighSymbols];
3164 + UInt32 prices[LZMA_NUM_PB_STATES_MAX][kLenNumSymbolsTotal];
3166 + UInt32 counters[LZMA_NUM_PB_STATES_MAX];
3178 + ISeqOutStream *outStream;
3185 + CLzmaProb *litProbs;
3187 + CLzmaProb isMatch[kNumStates][LZMA_NUM_PB_STATES_MAX];
3188 + CLzmaProb isRep[kNumStates];
3189 + CLzmaProb isRepG0[kNumStates];
3190 + CLzmaProb isRepG1[kNumStates];
3191 + CLzmaProb isRepG2[kNumStates];
3192 + CLzmaProb isRep0Long[kNumStates][LZMA_NUM_PB_STATES_MAX];
3194 + CLzmaProb posSlotEncoder[kNumLenToPosStates][1 << kNumPosSlotBits];
3195 + CLzmaProb posEncoders[kNumFullDistances - kEndPosModelIndex];
3196 + CLzmaProb posAlignEncoder[1 << kNumAlignBits];
3198 + CLenPriceEnc lenEnc;
3199 + CLenPriceEnc repLenEnc;
3201 + UInt32 reps[LZMA_NUM_REPS];
3207 + IMatchFinder matchFinder;
3208 + void *matchFinderObj;
3212 + CMatchFinderMt matchFinderMt;
3215 + CMatchFinder matchFinderBase;
3221 + UInt32 optimumEndIndex;
3222 + UInt32 optimumCurrentIndex;
3224 + UInt32 longestMatchLength;
3227 + COptimal opt[kNumOpts];
3229 + #ifndef LZMA_LOG_BSR
3230 + Byte g_FastPos[1 << kNumLogBits];
3233 + UInt32 ProbPrices[kBitModelTotal >> kNumMoveReducingBits];
3234 + UInt32 matches[LZMA_MATCH_LEN_MAX * 2 + 2 + 1];
3235 + UInt32 numFastBytes;
3236 + UInt32 additionalOffset;
3237 + UInt32 reps[LZMA_NUM_REPS];
3240 + UInt32 posSlotPrices[kNumLenToPosStates][kDistTableSizeMax];
3241 + UInt32 distancesPrices[kNumLenToPosStates][kNumFullDistances];
3242 + UInt32 alignPrices[kAlignTableSize];
3243 + UInt32 alignPriceCount;
3245 + UInt32 distTableSize;
3247 + unsigned lc, lp, pb;
3248 + unsigned lpMask, pbMask;
3250 + CLzmaProb *litProbs;
3252 + CLzmaProb isMatch[kNumStates][LZMA_NUM_PB_STATES_MAX];
3253 + CLzmaProb isRep[kNumStates];
3254 + CLzmaProb isRepG0[kNumStates];
3255 + CLzmaProb isRepG1[kNumStates];
3256 + CLzmaProb isRepG2[kNumStates];
3257 + CLzmaProb isRep0Long[kNumStates][LZMA_NUM_PB_STATES_MAX];
3259 + CLzmaProb posSlotEncoder[kNumLenToPosStates][1 << kNumPosSlotBits];
3260 + CLzmaProb posEncoders[kNumFullDistances - kEndPosModelIndex];
3261 + CLzmaProb posAlignEncoder[1 << kNumAlignBits];
3263 + CLenPriceEnc lenEnc;
3264 + CLenPriceEnc repLenEnc;
3272 + Bool writeEndMark;
3274 + UInt32 matchPriceCount;
3280 + UInt32 matchFinderCycles;
3284 + CSaveState saveState;
3287 +void LzmaEnc_SaveState(CLzmaEncHandle pp)
3289 + CLzmaEnc *p = (CLzmaEnc *)pp;
3290 + CSaveState *dest = &p->saveState;
3292 + dest->lenEnc = p->lenEnc;
3293 + dest->repLenEnc = p->repLenEnc;
3294 + dest->state = p->state;
3296 + for (i = 0; i < kNumStates; i++)
3298 + memcpy(dest->isMatch[i], p->isMatch[i], sizeof(p->isMatch[i]));
3299 + memcpy(dest->isRep0Long[i], p->isRep0Long[i], sizeof(p->isRep0Long[i]));
3301 + for (i = 0; i < kNumLenToPosStates; i++)
3302 + memcpy(dest->posSlotEncoder[i], p->posSlotEncoder[i], sizeof(p->posSlotEncoder[i]));
3303 + memcpy(dest->isRep, p->isRep, sizeof(p->isRep));
3304 + memcpy(dest->isRepG0, p->isRepG0, sizeof(p->isRepG0));
3305 + memcpy(dest->isRepG1, p->isRepG1, sizeof(p->isRepG1));
3306 + memcpy(dest->isRepG2, p->isRepG2, sizeof(p->isRepG2));
3307 + memcpy(dest->posEncoders, p->posEncoders, sizeof(p->posEncoders));
3308 + memcpy(dest->posAlignEncoder, p->posAlignEncoder, sizeof(p->posAlignEncoder));
3309 + memcpy(dest->reps, p->reps, sizeof(p->reps));
3310 + memcpy(dest->litProbs, p->litProbs, (0x300 << p->lclp) * sizeof(CLzmaProb));
3313 +void LzmaEnc_RestoreState(CLzmaEncHandle pp)
3315 + CLzmaEnc *dest = (CLzmaEnc *)pp;
3316 + const CSaveState *p = &dest->saveState;
3318 + dest->lenEnc = p->lenEnc;
3319 + dest->repLenEnc = p->repLenEnc;
3320 + dest->state = p->state;
3322 + for (i = 0; i < kNumStates; i++)
3324 + memcpy(dest->isMatch[i], p->isMatch[i], sizeof(p->isMatch[i]));
3325 + memcpy(dest->isRep0Long[i], p->isRep0Long[i], sizeof(p->isRep0Long[i]));
3327 + for (i = 0; i < kNumLenToPosStates; i++)
3328 + memcpy(dest->posSlotEncoder[i], p->posSlotEncoder[i], sizeof(p->posSlotEncoder[i]));
3329 + memcpy(dest->isRep, p->isRep, sizeof(p->isRep));
3330 + memcpy(dest->isRepG0, p->isRepG0, sizeof(p->isRepG0));
3331 + memcpy(dest->isRepG1, p->isRepG1, sizeof(p->isRepG1));
3332 + memcpy(dest->isRepG2, p->isRepG2, sizeof(p->isRepG2));
3333 + memcpy(dest->posEncoders, p->posEncoders, sizeof(p->posEncoders));
3334 + memcpy(dest->posAlignEncoder, p->posAlignEncoder, sizeof(p->posAlignEncoder));
3335 + memcpy(dest->reps, p->reps, sizeof(p->reps));
3336 + memcpy(dest->litProbs, p->litProbs, (0x300 << dest->lclp) * sizeof(CLzmaProb));
3339 +SRes LzmaEnc_SetProps(CLzmaEncHandle pp, const CLzmaEncProps *props2)
3341 + CLzmaEnc *p = (CLzmaEnc *)pp;
3342 + CLzmaEncProps props = *props2;
3343 + LzmaEncProps_Normalize(&props);
3345 + if (props.lc > LZMA_LC_MAX || props.lp > LZMA_LP_MAX || props.pb > LZMA_PB_MAX ||
3346 + props.dictSize > (1 << kDicLogSizeMaxCompress) || props.dictSize > (1 << 30))
3347 + return SZ_ERROR_PARAM;
3348 + p->dictSize = props.dictSize;
3349 + p->matchFinderCycles = props.mc;
3351 + unsigned fb = props.fb;
3354 + if (fb > LZMA_MATCH_LEN_MAX)
3355 + fb = LZMA_MATCH_LEN_MAX;
3356 + p->numFastBytes = fb;
3361 + p->fastMode = (props.algo == 0);
3362 + p->matchFinderBase.btMode = props.btMode;
3364 + UInt32 numHashBytes = 4;
3367 + if (props.numHashBytes < 2)
3369 + else if (props.numHashBytes < 4)
3370 + numHashBytes = props.numHashBytes;
3372 + p->matchFinderBase.numHashBytes = numHashBytes;
3375 + p->matchFinderBase.cutValue = props.mc;
3377 + p->writeEndMark = props.writeEndMark;
3381 + if (newMultiThread != _multiThread)
3383 + ReleaseMatchFinder();
3384 + _multiThread = newMultiThread;
3387 + p->multiThread = (props.numThreads > 1);
3393 +static const int kLiteralNextStates[kNumStates] = {0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 4, 5};
3394 +static const int kMatchNextStates[kNumStates] = {7, 7, 7, 7, 7, 7, 7, 10, 10, 10, 10, 10};
3395 +static const int kRepNextStates[kNumStates] = {8, 8, 8, 8, 8, 8, 8, 11, 11, 11, 11, 11};
3396 +static const int kShortRepNextStates[kNumStates]= {9, 9, 9, 9, 9, 9, 9, 11, 11, 11, 11, 11};
3398 +#define IsCharState(s) ((s) < 7)
3400 +#define GetLenToPosState(len) (((len) < kNumLenToPosStates + 1) ? (len) - 2 : kNumLenToPosStates - 1)
3402 +#define kInfinityPrice (1 << 30)
3404 +static void RangeEnc_Construct(CRangeEnc *p)
3410 +#define RangeEnc_GetProcessed(p) ((p)->processed + ((p)->buf - (p)->bufBase) + (p)->cacheSize)
3412 +#define RC_BUF_SIZE (1 << 16)
3413 +static int RangeEnc_Alloc(CRangeEnc *p, ISzAlloc *alloc)
3415 + if (p->bufBase == 0)
3417 + p->bufBase = (Byte *)alloc->Alloc(alloc, RC_BUF_SIZE);
3418 + if (p->bufBase == 0)
3420 + p->bufLim = p->bufBase + RC_BUF_SIZE;
3425 +static void RangeEnc_Free(CRangeEnc *p, ISzAlloc *alloc)
3427 + alloc->Free(alloc, p->bufBase);
3431 +static void RangeEnc_Init(CRangeEnc *p)
3433 + /* Stream.Init(); */
3435 + p->range = 0xFFFFFFFF;
3439 + p->buf = p->bufBase;
3445 +static void RangeEnc_FlushStream(CRangeEnc *p)
3448 + if (p->res != SZ_OK)
3450 + num = p->buf - p->bufBase;
3451 + if (num != p->outStream->Write(p->outStream, p->bufBase, num))
3452 + p->res = SZ_ERROR_WRITE;
3453 + p->processed += num;
3454 + p->buf = p->bufBase;
3457 +static void MY_FAST_CALL RangeEnc_ShiftLow(CRangeEnc *p)
3459 + if ((UInt32)p->low < (UInt32)0xFF000000 || (int)(p->low >> 32) != 0)
3461 + Byte temp = p->cache;
3464 + Byte *buf = p->buf;
3465 + *buf++ = (Byte)(temp + (Byte)(p->low >> 32));
3467 + if (buf == p->bufLim)
3468 + RangeEnc_FlushStream(p);
3471 + while (--p->cacheSize != 0);
3472 + p->cache = (Byte)((UInt32)p->low >> 24);
3475 + p->low = (UInt32)p->low << 8;
3478 +static void RangeEnc_FlushData(CRangeEnc *p)
3481 + for (i = 0; i < 5; i++)
3482 + RangeEnc_ShiftLow(p);
3485 +static void RangeEnc_EncodeDirectBits(CRangeEnc *p, UInt32 value, int numBits)
3490 + p->low += p->range & (0 - ((value >> --numBits) & 1));
3491 + if (p->range < kTopValue)
3494 + RangeEnc_ShiftLow(p);
3497 + while (numBits != 0);
3500 +static void RangeEnc_EncodeBit(CRangeEnc *p, CLzmaProb *prob, UInt32 symbol)
3502 + UInt32 ttt = *prob;
3503 + UInt32 newBound = (p->range >> kNumBitModelTotalBits) * ttt;
3506 + p->range = newBound;
3507 + ttt += (kBitModelTotal - ttt) >> kNumMoveBits;
3511 + p->low += newBound;
3512 + p->range -= newBound;
3513 + ttt -= ttt >> kNumMoveBits;
3515 + *prob = (CLzmaProb)ttt;
3516 + if (p->range < kTopValue)
3519 + RangeEnc_ShiftLow(p);
3523 +static void LitEnc_Encode(CRangeEnc *p, CLzmaProb *probs, UInt32 symbol)
3528 + RangeEnc_EncodeBit(p, probs + (symbol >> 8), (symbol >> 7) & 1);
3531 + while (symbol < 0x10000);
3534 +static void LitEnc_EncodeMatched(CRangeEnc *p, CLzmaProb *probs, UInt32 symbol, UInt32 matchByte)
3536 + UInt32 offs = 0x100;
3541 + RangeEnc_EncodeBit(p, probs + (offs + (matchByte & offs) + (symbol >> 8)), (symbol >> 7) & 1);
3543 + offs &= ~(matchByte ^ symbol);
3545 + while (symbol < 0x10000);
3548 +void LzmaEnc_InitPriceTables(UInt32 *ProbPrices)
3551 + for (i = (1 << kNumMoveReducingBits) / 2; i < kBitModelTotal; i += (1 << kNumMoveReducingBits))
3553 + const int kCyclesBits = kNumBitPriceShiftBits;
3555 + UInt32 bitCount = 0;
3557 + for (j = 0; j < kCyclesBits; j++)
3561 + while (w >= ((UInt32)1 << 16))
3567 + ProbPrices[i >> kNumMoveReducingBits] = ((kNumBitModelTotalBits << kCyclesBits) - 15 - bitCount);
3572 +#define GET_PRICE(prob, symbol) \
3573 + p->ProbPrices[((prob) ^ (((-(int)(symbol))) & (kBitModelTotal - 1))) >> kNumMoveReducingBits];
3575 +#define GET_PRICEa(prob, symbol) \
3576 + ProbPrices[((prob) ^ ((-((int)(symbol))) & (kBitModelTotal - 1))) >> kNumMoveReducingBits];
3578 +#define GET_PRICE_0(prob) p->ProbPrices[(prob) >> kNumMoveReducingBits]
3579 +#define GET_PRICE_1(prob) p->ProbPrices[((prob) ^ (kBitModelTotal - 1)) >> kNumMoveReducingBits]
3581 +#define GET_PRICE_0a(prob) ProbPrices[(prob) >> kNumMoveReducingBits]
3582 +#define GET_PRICE_1a(prob) ProbPrices[((prob) ^ (kBitModelTotal - 1)) >> kNumMoveReducingBits]
3584 +static UInt32 LitEnc_GetPrice(const CLzmaProb *probs, UInt32 symbol, UInt32 *ProbPrices)
3590 + price += GET_PRICEa(probs[symbol >> 8], (symbol >> 7) & 1);
3593 + while (symbol < 0x10000);
3597 +static UInt32 LitEnc_GetPriceMatched(const CLzmaProb *probs, UInt32 symbol, UInt32 matchByte, UInt32 *ProbPrices)
3600 + UInt32 offs = 0x100;
3605 + price += GET_PRICEa(probs[offs + (matchByte & offs) + (symbol >> 8)], (symbol >> 7) & 1);
3607 + offs &= ~(matchByte ^ symbol);
3609 + while (symbol < 0x10000);
3614 +static void RcTree_Encode(CRangeEnc *rc, CLzmaProb *probs, int numBitLevels, UInt32 symbol)
3618 + for (i = numBitLevels; i != 0;)
3622 + bit = (symbol >> i) & 1;
3623 + RangeEnc_EncodeBit(rc, probs + m, bit);
3624 + m = (m << 1) | bit;
3628 +static void RcTree_ReverseEncode(CRangeEnc *rc, CLzmaProb *probs, int numBitLevels, UInt32 symbol)
3632 + for (i = 0; i < numBitLevels; i++)
3634 + UInt32 bit = symbol & 1;
3635 + RangeEnc_EncodeBit(rc, probs + m, bit);
3636 + m = (m << 1) | bit;
3641 +static UInt32 RcTree_GetPrice(const CLzmaProb *probs, int numBitLevels, UInt32 symbol, UInt32 *ProbPrices)
3644 + symbol |= (1 << numBitLevels);
3645 + while (symbol != 1)
3647 + price += GET_PRICEa(probs[symbol >> 1], symbol & 1);
3653 +static UInt32 RcTree_ReverseGetPrice(const CLzmaProb *probs, int numBitLevels, UInt32 symbol, UInt32 *ProbPrices)
3658 + for (i = numBitLevels; i != 0; i--)
3660 + UInt32 bit = symbol & 1;
3662 + price += GET_PRICEa(probs[m], bit);
3663 + m = (m << 1) | bit;
3669 +static void LenEnc_Init(CLenEnc *p)
3672 + p->choice = p->choice2 = kProbInitValue;
3673 + for (i = 0; i < (LZMA_NUM_PB_STATES_MAX << kLenNumLowBits); i++)
3674 + p->low[i] = kProbInitValue;
3675 + for (i = 0; i < (LZMA_NUM_PB_STATES_MAX << kLenNumMidBits); i++)
3676 + p->mid[i] = kProbInitValue;
3677 + for (i = 0; i < kLenNumHighSymbols; i++)
3678 + p->high[i] = kProbInitValue;
3681 +static void LenEnc_Encode(CLenEnc *p, CRangeEnc *rc, UInt32 symbol, UInt32 posState)
3683 + if (symbol < kLenNumLowSymbols)
3685 + RangeEnc_EncodeBit(rc, &p->choice, 0);
3686 + RcTree_Encode(rc, p->low + (posState << kLenNumLowBits), kLenNumLowBits, symbol);
3690 + RangeEnc_EncodeBit(rc, &p->choice, 1);
3691 + if (symbol < kLenNumLowSymbols + kLenNumMidSymbols)
3693 + RangeEnc_EncodeBit(rc, &p->choice2, 0);
3694 + RcTree_Encode(rc, p->mid + (posState << kLenNumMidBits), kLenNumMidBits, symbol - kLenNumLowSymbols);
3698 + RangeEnc_EncodeBit(rc, &p->choice2, 1);
3699 + RcTree_Encode(rc, p->high, kLenNumHighBits, symbol - kLenNumLowSymbols - kLenNumMidSymbols);
3704 +static void LenEnc_SetPrices(CLenEnc *p, UInt32 posState, UInt32 numSymbols, UInt32 *prices, UInt32 *ProbPrices)
3706 + UInt32 a0 = GET_PRICE_0a(p->choice);
3707 + UInt32 a1 = GET_PRICE_1a(p->choice);
3708 + UInt32 b0 = a1 + GET_PRICE_0a(p->choice2);
3709 + UInt32 b1 = a1 + GET_PRICE_1a(p->choice2);
3711 + for (i = 0; i < kLenNumLowSymbols; i++)
3713 + if (i >= numSymbols)
3715 + prices[i] = a0 + RcTree_GetPrice(p->low + (posState << kLenNumLowBits), kLenNumLowBits, i, ProbPrices);
3717 + for (; i < kLenNumLowSymbols + kLenNumMidSymbols; i++)
3719 + if (i >= numSymbols)
3721 + prices[i] = b0 + RcTree_GetPrice(p->mid + (posState << kLenNumMidBits), kLenNumMidBits, i - kLenNumLowSymbols, ProbPrices);
3723 + for (; i < numSymbols; i++)
3724 + prices[i] = b1 + RcTree_GetPrice(p->high, kLenNumHighBits, i - kLenNumLowSymbols - kLenNumMidSymbols, ProbPrices);
3727 +static void MY_FAST_CALL LenPriceEnc_UpdateTable(CLenPriceEnc *p, UInt32 posState, UInt32 *ProbPrices)
3729 + LenEnc_SetPrices(&p->p, posState, p->tableSize, p->prices[posState], ProbPrices);
3730 + p->counters[posState] = p->tableSize;
3733 +static void LenPriceEnc_UpdateTables(CLenPriceEnc *p, UInt32 numPosStates, UInt32 *ProbPrices)
3736 + for (posState = 0; posState < numPosStates; posState++)
3737 + LenPriceEnc_UpdateTable(p, posState, ProbPrices);
3740 +static void LenEnc_Encode2(CLenPriceEnc *p, CRangeEnc *rc, UInt32 symbol, UInt32 posState, Bool updatePrice, UInt32 *ProbPrices)
3742 + LenEnc_Encode(&p->p, rc, symbol, posState);
3744 + if (--p->counters[posState] == 0)
3745 + LenPriceEnc_UpdateTable(p, posState, ProbPrices);
3751 +static void MovePos(CLzmaEnc *p, UInt32 num)
3755 + printf("\n MovePos %d", num);
3759 + p->additionalOffset += num;
3760 + p->matchFinder.Skip(p->matchFinderObj, num);
3764 +static UInt32 ReadMatchDistances(CLzmaEnc *p, UInt32 *numDistancePairsRes)
3766 + UInt32 lenRes = 0, numPairs;
3767 + p->numAvail = p->matchFinder.GetNumAvailableBytes(p->matchFinderObj);
3768 + numPairs = p->matchFinder.GetMatches(p->matchFinderObj, p->matches);
3770 + printf("\n i = %d numPairs = %d ", ttt, numPairs / 2);
3774 + for (i = 0; i < numPairs; i += 2)
3775 + printf("%2d %6d | ", p->matches[i], p->matches[i + 1]);
3780 + lenRes = p->matches[numPairs - 2];
3781 + if (lenRes == p->numFastBytes)
3783 + const Byte *pby = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - 1;
3784 + UInt32 distance = p->matches[numPairs - 1] + 1;
3785 + UInt32 numAvail = p->numAvail;
3786 + if (numAvail > LZMA_MATCH_LEN_MAX)
3787 + numAvail = LZMA_MATCH_LEN_MAX;
3789 + const Byte *pby2 = pby - distance;
3790 + for (; lenRes < numAvail && pby[lenRes] == pby2[lenRes]; lenRes++);
3794 + p->additionalOffset++;
3795 + *numDistancePairsRes = numPairs;
3800 +#define MakeAsChar(p) (p)->backPrev = (UInt32)(-1); (p)->prev1IsChar = False;
3801 +#define MakeAsShortRep(p) (p)->backPrev = 0; (p)->prev1IsChar = False;
3802 +#define IsShortRep(p) ((p)->backPrev == 0)
3804 +static UInt32 GetRepLen1Price(CLzmaEnc *p, UInt32 state, UInt32 posState)
3807 + GET_PRICE_0(p->isRepG0[state]) +
3808 + GET_PRICE_0(p->isRep0Long[state][posState]);
3811 +static UInt32 GetPureRepPrice(CLzmaEnc *p, UInt32 repIndex, UInt32 state, UInt32 posState)
3814 + if (repIndex == 0)
3816 + price = GET_PRICE_0(p->isRepG0[state]);
3817 + price += GET_PRICE_1(p->isRep0Long[state][posState]);
3821 + price = GET_PRICE_1(p->isRepG0[state]);
3822 + if (repIndex == 1)
3823 + price += GET_PRICE_0(p->isRepG1[state]);
3826 + price += GET_PRICE_1(p->isRepG1[state]);
3827 + price += GET_PRICE(p->isRepG2[state], repIndex - 2);
3833 +static UInt32 GetRepPrice(CLzmaEnc *p, UInt32 repIndex, UInt32 len, UInt32 state, UInt32 posState)
3835 + return p->repLenEnc.prices[posState][len - LZMA_MATCH_LEN_MIN] +
3836 + GetPureRepPrice(p, repIndex, state, posState);
3839 +static UInt32 Backward(CLzmaEnc *p, UInt32 *backRes, UInt32 cur)
3841 + UInt32 posMem = p->opt[cur].posPrev;
3842 + UInt32 backMem = p->opt[cur].backPrev;
3843 + p->optimumEndIndex = cur;
3846 + if (p->opt[cur].prev1IsChar)
3848 + MakeAsChar(&p->opt[posMem])
3849 + p->opt[posMem].posPrev = posMem - 1;
3850 + if (p->opt[cur].prev2)
3852 + p->opt[posMem - 1].prev1IsChar = False;
3853 + p->opt[posMem - 1].posPrev = p->opt[cur].posPrev2;
3854 + p->opt[posMem - 1].backPrev = p->opt[cur].backPrev2;
3858 + UInt32 posPrev = posMem;
3859 + UInt32 backCur = backMem;
3861 + backMem = p->opt[posPrev].backPrev;
3862 + posMem = p->opt[posPrev].posPrev;
3864 + p->opt[posPrev].backPrev = backCur;
3865 + p->opt[posPrev].posPrev = cur;
3870 + *backRes = p->opt[0].backPrev;
3871 + p->optimumCurrentIndex = p->opt[0].posPrev;
3872 + return p->optimumCurrentIndex;
3875 +#define LIT_PROBS(pos, prevByte) (p->litProbs + ((((pos) & p->lpMask) << p->lc) + ((prevByte) >> (8 - p->lc))) * 0x300)
3877 +static UInt32 GetOptimum(CLzmaEnc *p, UInt32 position, UInt32 *backRes)
3879 + UInt32 numAvail, mainLen, numPairs, repMaxIndex, i, posState, lenEnd, len, cur;
3880 + UInt32 matchPrice, repMatchPrice, normalMatchPrice;
3881 + UInt32 reps[LZMA_NUM_REPS], repLens[LZMA_NUM_REPS];
3884 + Byte curByte, matchByte;
3885 + if (p->optimumEndIndex != p->optimumCurrentIndex)
3887 + const COptimal *opt = &p->opt[p->optimumCurrentIndex];
3888 + UInt32 lenRes = opt->posPrev - p->optimumCurrentIndex;
3889 + *backRes = opt->backPrev;
3890 + p->optimumCurrentIndex = opt->posPrev;
3893 + p->optimumCurrentIndex = p->optimumEndIndex = 0;
3895 + if (p->additionalOffset == 0)
3896 + mainLen = ReadMatchDistances(p, &numPairs);
3899 + mainLen = p->longestMatchLength;
3900 + numPairs = p->numPairs;
3903 + numAvail = p->numAvail;
3906 + *backRes = (UInt32)(-1);
3909 + if (numAvail > LZMA_MATCH_LEN_MAX)
3910 + numAvail = LZMA_MATCH_LEN_MAX;
3912 + data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - 1;
3914 + for (i = 0; i < LZMA_NUM_REPS; i++)
3917 + const Byte *data2;
3918 + reps[i] = p->reps[i];
3919 + data2 = data - (reps[i] + 1);
3920 + if (data[0] != data2[0] || data[1] != data2[1])
3925 + for (lenTest = 2; lenTest < numAvail && data[lenTest] == data2[lenTest]; lenTest++);
3926 + repLens[i] = lenTest;
3927 + if (lenTest > repLens[repMaxIndex])
3930 + if (repLens[repMaxIndex] >= p->numFastBytes)
3933 + *backRes = repMaxIndex;
3934 + lenRes = repLens[repMaxIndex];
3935 + MovePos(p, lenRes - 1);
3939 + matches = p->matches;
3940 + if (mainLen >= p->numFastBytes)
3942 + *backRes = matches[numPairs - 1] + LZMA_NUM_REPS;
3943 + MovePos(p, mainLen - 1);
3947 + matchByte = *(data - (reps[0] + 1));
3949 + if (mainLen < 2 && curByte != matchByte && repLens[repMaxIndex] < 2)
3951 + *backRes = (UInt32)-1;
3955 + p->opt[0].state = (CState)p->state;
3957 + posState = (position & p->pbMask);
3960 + const CLzmaProb *probs = LIT_PROBS(position, *(data - 1));
3961 + p->opt[1].price = GET_PRICE_0(p->isMatch[p->state][posState]) +
3962 + (!IsCharState(p->state) ?
3963 + LitEnc_GetPriceMatched(probs, curByte, matchByte, p->ProbPrices) :
3964 + LitEnc_GetPrice(probs, curByte, p->ProbPrices));
3967 + MakeAsChar(&p->opt[1]);
3969 + matchPrice = GET_PRICE_1(p->isMatch[p->state][posState]);
3970 + repMatchPrice = matchPrice + GET_PRICE_1(p->isRep[p->state]);
3972 + if (matchByte == curByte)
3974 + UInt32 shortRepPrice = repMatchPrice + GetRepLen1Price(p, p->state, posState);
3975 + if (shortRepPrice < p->opt[1].price)
3977 + p->opt[1].price = shortRepPrice;
3978 + MakeAsShortRep(&p->opt[1]);
3981 + lenEnd = ((mainLen >= repLens[repMaxIndex]) ? mainLen : repLens[repMaxIndex]);
3985 + *backRes = p->opt[1].backPrev;
3989 + p->opt[1].posPrev = 0;
3990 + for (i = 0; i < LZMA_NUM_REPS; i++)
3991 + p->opt[0].backs[i] = reps[i];
3995 + p->opt[len--].price = kInfinityPrice;
3998 + for (i = 0; i < LZMA_NUM_REPS; i++)
4000 + UInt32 repLen = repLens[i];
4004 + price = repMatchPrice + GetPureRepPrice(p, i, p->state, posState);
4007 + UInt32 curAndLenPrice = price + p->repLenEnc.prices[posState][repLen - 2];
4008 + COptimal *opt = &p->opt[repLen];
4009 + if (curAndLenPrice < opt->price)
4011 + opt->price = curAndLenPrice;
4013 + opt->backPrev = i;
4014 + opt->prev1IsChar = False;
4017 + while (--repLen >= 2);
4020 + normalMatchPrice = matchPrice + GET_PRICE_0(p->isRep[p->state]);
4022 + len = ((repLens[0] >= 2) ? repLens[0] + 1 : 2);
4023 + if (len <= mainLen)
4026 + while (len > matches[offs])
4031 + UInt32 distance = matches[offs + 1];
4033 + UInt32 curAndLenPrice = normalMatchPrice + p->lenEnc.prices[posState][len - LZMA_MATCH_LEN_MIN];
4034 + UInt32 lenToPosState = GetLenToPosState(len);
4035 + if (distance < kNumFullDistances)
4036 + curAndLenPrice += p->distancesPrices[lenToPosState][distance];
4040 + GetPosSlot2(distance, slot);
4041 + curAndLenPrice += p->alignPrices[distance & kAlignMask] + p->posSlotPrices[lenToPosState][slot];
4043 + opt = &p->opt[len];
4044 + if (curAndLenPrice < opt->price)
4046 + opt->price = curAndLenPrice;
4048 + opt->backPrev = distance + LZMA_NUM_REPS;
4049 + opt->prev1IsChar = False;
4051 + if (len == matches[offs])
4054 + if (offs == numPairs)
4063 + if (position >= 0)
4066 + printf("\n pos = %4X", position);
4067 + for (i = cur; i <= lenEnd; i++)
4068 + printf("\nprice[%4X] = %d", position - cur + i, p->opt[i].price);
4074 + UInt32 numAvailFull, newLen, numPairs, posPrev, state, posState, startLen;
4075 + UInt32 curPrice, curAnd1Price, matchPrice, repMatchPrice;
4077 + Byte curByte, matchByte;
4080 + COptimal *nextOpt;
4083 + if (cur == lenEnd)
4084 + return Backward(p, backRes, cur);
4086 + newLen = ReadMatchDistances(p, &numPairs);
4087 + if (newLen >= p->numFastBytes)
4089 + p->numPairs = numPairs;
4090 + p->longestMatchLength = newLen;
4091 + return Backward(p, backRes, cur);
4094 + curOpt = &p->opt[cur];
4095 + posPrev = curOpt->posPrev;
4096 + if (curOpt->prev1IsChar)
4099 + if (curOpt->prev2)
4101 + state = p->opt[curOpt->posPrev2].state;
4102 + if (curOpt->backPrev2 < LZMA_NUM_REPS)
4103 + state = kRepNextStates[state];
4105 + state = kMatchNextStates[state];
4108 + state = p->opt[posPrev].state;
4109 + state = kLiteralNextStates[state];
4112 + state = p->opt[posPrev].state;
4113 + if (posPrev == cur - 1)
4115 + if (IsShortRep(curOpt))
4116 + state = kShortRepNextStates[state];
4118 + state = kLiteralNextStates[state];
4123 + const COptimal *prevOpt;
4124 + if (curOpt->prev1IsChar && curOpt->prev2)
4126 + posPrev = curOpt->posPrev2;
4127 + pos = curOpt->backPrev2;
4128 + state = kRepNextStates[state];
4132 + pos = curOpt->backPrev;
4133 + if (pos < LZMA_NUM_REPS)
4134 + state = kRepNextStates[state];
4136 + state = kMatchNextStates[state];
4138 + prevOpt = &p->opt[posPrev];
4139 + if (pos < LZMA_NUM_REPS)
4142 + reps[0] = prevOpt->backs[pos];
4143 + for (i = 1; i <= pos; i++)
4144 + reps[i] = prevOpt->backs[i - 1];
4145 + for (; i < LZMA_NUM_REPS; i++)
4146 + reps[i] = prevOpt->backs[i];
4151 + reps[0] = (pos - LZMA_NUM_REPS);
4152 + for (i = 1; i < LZMA_NUM_REPS; i++)
4153 + reps[i] = prevOpt->backs[i - 1];
4156 + curOpt->state = (CState)state;
4158 + curOpt->backs[0] = reps[0];
4159 + curOpt->backs[1] = reps[1];
4160 + curOpt->backs[2] = reps[2];
4161 + curOpt->backs[3] = reps[3];
4163 + curPrice = curOpt->price;
4164 + nextIsChar = False;
4165 + data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - 1;
4167 + matchByte = *(data - (reps[0] + 1));
4169 + posState = (position & p->pbMask);
4171 + curAnd1Price = curPrice + GET_PRICE_0(p->isMatch[state][posState]);
4173 + const CLzmaProb *probs = LIT_PROBS(position, *(data - 1));
4175 + (!IsCharState(state) ?
4176 + LitEnc_GetPriceMatched(probs, curByte, matchByte, p->ProbPrices) :
4177 + LitEnc_GetPrice(probs, curByte, p->ProbPrices));
4180 + nextOpt = &p->opt[cur + 1];
4182 + if (curAnd1Price < nextOpt->price)
4184 + nextOpt->price = curAnd1Price;
4185 + nextOpt->posPrev = cur;
4186 + MakeAsChar(nextOpt);
4187 + nextIsChar = True;
4190 + matchPrice = curPrice + GET_PRICE_1(p->isMatch[state][posState]);
4191 + repMatchPrice = matchPrice + GET_PRICE_1(p->isRep[state]);
4193 + if (matchByte == curByte && !(nextOpt->posPrev < cur && nextOpt->backPrev == 0))
4195 + UInt32 shortRepPrice = repMatchPrice + GetRepLen1Price(p, state, posState);
4196 + if (shortRepPrice <= nextOpt->price)
4198 + nextOpt->price = shortRepPrice;
4199 + nextOpt->posPrev = cur;
4200 + MakeAsShortRep(nextOpt);
4201 + nextIsChar = True;
4204 + numAvailFull = p->numAvail;
4206 + UInt32 temp = kNumOpts - 1 - cur;
4207 + if (temp < numAvailFull)
4208 + numAvailFull = temp;
4211 + if (numAvailFull < 2)
4213 + numAvail = (numAvailFull <= p->numFastBytes ? numAvailFull : p->numFastBytes);
4215 + if (!nextIsChar && matchByte != curByte) /* speed optimization */
4217 + /* try Literal + rep0 */
4220 + const Byte *data2 = data - (reps[0] + 1);
4221 + UInt32 limit = p->numFastBytes + 1;
4222 + if (limit > numAvailFull)
4223 + limit = numAvailFull;
4225 + for (temp = 1; temp < limit && data[temp] == data2[temp]; temp++);
4226 + lenTest2 = temp - 1;
4227 + if (lenTest2 >= 2)
4229 + UInt32 state2 = kLiteralNextStates[state];
4230 + UInt32 posStateNext = (position + 1) & p->pbMask;
4231 + UInt32 nextRepMatchPrice = curAnd1Price +
4232 + GET_PRICE_1(p->isMatch[state2][posStateNext]) +
4233 + GET_PRICE_1(p->isRep[state2]);
4234 + /* for (; lenTest2 >= 2; lenTest2--) */
4236 + UInt32 curAndLenPrice;
4238 + UInt32 offset = cur + 1 + lenTest2;
4239 + while (lenEnd < offset)
4240 + p->opt[++lenEnd].price = kInfinityPrice;
4241 + curAndLenPrice = nextRepMatchPrice + GetRepPrice(p, 0, lenTest2, state2, posStateNext);
4242 + opt = &p->opt[offset];
4243 + if (curAndLenPrice < opt->price)
4245 + opt->price = curAndLenPrice;
4246 + opt->posPrev = cur + 1;
4247 + opt->backPrev = 0;
4248 + opt->prev1IsChar = True;
4249 + opt->prev2 = False;
4255 + startLen = 2; /* speed optimization */
4258 + for (repIndex = 0; repIndex < LZMA_NUM_REPS; repIndex++)
4261 + UInt32 lenTestTemp;
4263 + const Byte *data2 = data - (reps[repIndex] + 1);
4264 + if (data[0] != data2[0] || data[1] != data2[1])
4266 + for (lenTest = 2; lenTest < numAvail && data[lenTest] == data2[lenTest]; lenTest++);
4267 + while (lenEnd < cur + lenTest)
4268 + p->opt[++lenEnd].price = kInfinityPrice;
4269 + lenTestTemp = lenTest;
4270 + price = repMatchPrice + GetPureRepPrice(p, repIndex, state, posState);
4273 + UInt32 curAndLenPrice = price + p->repLenEnc.prices[posState][lenTest - 2];
4274 + COptimal *opt = &p->opt[cur + lenTest];
4275 + if (curAndLenPrice < opt->price)
4277 + opt->price = curAndLenPrice;
4278 + opt->posPrev = cur;
4279 + opt->backPrev = repIndex;
4280 + opt->prev1IsChar = False;
4283 + while (--lenTest >= 2);
4284 + lenTest = lenTestTemp;
4286 + if (repIndex == 0)
4287 + startLen = lenTest + 1;
4289 + /* if (_maxMode) */
4291 + UInt32 lenTest2 = lenTest + 1;
4292 + UInt32 limit = lenTest2 + p->numFastBytes;
4293 + UInt32 nextRepMatchPrice;
4294 + if (limit > numAvailFull)
4295 + limit = numAvailFull;
4296 + for (; lenTest2 < limit && data[lenTest2] == data2[lenTest2]; lenTest2++);
4297 + lenTest2 -= lenTest + 1;
4298 + if (lenTest2 >= 2)
4300 + UInt32 state2 = kRepNextStates[state];
4301 + UInt32 posStateNext = (position + lenTest) & p->pbMask;
4302 + UInt32 curAndLenCharPrice =
4303 + price + p->repLenEnc.prices[posState][lenTest - 2] +
4304 + GET_PRICE_0(p->isMatch[state2][posStateNext]) +
4305 + LitEnc_GetPriceMatched(LIT_PROBS(position + lenTest, data[lenTest - 1]),
4306 + data[lenTest], data2[lenTest], p->ProbPrices);
4307 + state2 = kLiteralNextStates[state2];
4308 + posStateNext = (position + lenTest + 1) & p->pbMask;
4309 + nextRepMatchPrice = curAndLenCharPrice +
4310 + GET_PRICE_1(p->isMatch[state2][posStateNext]) +
4311 + GET_PRICE_1(p->isRep[state2]);
4313 + /* for (; lenTest2 >= 2; lenTest2--) */
4315 + UInt32 curAndLenPrice;
4317 + UInt32 offset = cur + lenTest + 1 + lenTest2;
4318 + while (lenEnd < offset)
4319 + p->opt[++lenEnd].price = kInfinityPrice;
4320 + curAndLenPrice = nextRepMatchPrice + GetRepPrice(p, 0, lenTest2, state2, posStateNext);
4321 + opt = &p->opt[offset];
4322 + if (curAndLenPrice < opt->price)
4324 + opt->price = curAndLenPrice;
4325 + opt->posPrev = cur + lenTest + 1;
4326 + opt->backPrev = 0;
4327 + opt->prev1IsChar = True;
4328 + opt->prev2 = True;
4329 + opt->posPrev2 = cur;
4330 + opt->backPrev2 = repIndex;
4337 + /* for (UInt32 lenTest = 2; lenTest <= newLen; lenTest++) */
4338 + if (newLen > numAvail)
4340 + newLen = numAvail;
4341 + for (numPairs = 0; newLen > matches[numPairs]; numPairs += 2);
4342 + matches[numPairs] = newLen;
4345 + if (newLen >= startLen)
4347 + UInt32 normalMatchPrice = matchPrice + GET_PRICE_0(p->isRep[state]);
4348 + UInt32 offs, curBack, posSlot;
4350 + while (lenEnd < cur + newLen)
4351 + p->opt[++lenEnd].price = kInfinityPrice;
4354 + while (startLen > matches[offs])
4356 + curBack = matches[offs + 1];
4357 + GetPosSlot2(curBack, posSlot);
4358 + for (lenTest = /*2*/ startLen; ; lenTest++)
4360 + UInt32 curAndLenPrice = normalMatchPrice + p->lenEnc.prices[posState][lenTest - LZMA_MATCH_LEN_MIN];
4361 + UInt32 lenToPosState = GetLenToPosState(lenTest);
4363 + if (curBack < kNumFullDistances)
4364 + curAndLenPrice += p->distancesPrices[lenToPosState][curBack];
4366 + curAndLenPrice += p->posSlotPrices[lenToPosState][posSlot] + p->alignPrices[curBack & kAlignMask];
4368 + opt = &p->opt[cur + lenTest];
4369 + if (curAndLenPrice < opt->price)
4371 + opt->price = curAndLenPrice;
4372 + opt->posPrev = cur;
4373 + opt->backPrev = curBack + LZMA_NUM_REPS;
4374 + opt->prev1IsChar = False;
4377 + if (/*_maxMode && */lenTest == matches[offs])
4379 + /* Try Match + Literal + Rep0 */
4380 + const Byte *data2 = data - (curBack + 1);
4381 + UInt32 lenTest2 = lenTest + 1;
4382 + UInt32 limit = lenTest2 + p->numFastBytes;
4383 + UInt32 nextRepMatchPrice;
4384 + if (limit > numAvailFull)
4385 + limit = numAvailFull;
4386 + for (; lenTest2 < limit && data[lenTest2] == data2[lenTest2]; lenTest2++);
4387 + lenTest2 -= lenTest + 1;
4388 + if (lenTest2 >= 2)
4390 + UInt32 state2 = kMatchNextStates[state];
4391 + UInt32 posStateNext = (position + lenTest) & p->pbMask;
4392 + UInt32 curAndLenCharPrice = curAndLenPrice +
4393 + GET_PRICE_0(p->isMatch[state2][posStateNext]) +
4394 + LitEnc_GetPriceMatched(LIT_PROBS(position + lenTest, data[lenTest - 1]),
4395 + data[lenTest], data2[lenTest], p->ProbPrices);
4396 + state2 = kLiteralNextStates[state2];
4397 + posStateNext = (posStateNext + 1) & p->pbMask;
4398 + nextRepMatchPrice = curAndLenCharPrice +
4399 + GET_PRICE_1(p->isMatch[state2][posStateNext]) +
4400 + GET_PRICE_1(p->isRep[state2]);
4402 + /* for (; lenTest2 >= 2; lenTest2--) */
4404 + UInt32 offset = cur + lenTest + 1 + lenTest2;
4405 + UInt32 curAndLenPrice;
4407 + while (lenEnd < offset)
4408 + p->opt[++lenEnd].price = kInfinityPrice;
4409 + curAndLenPrice = nextRepMatchPrice + GetRepPrice(p, 0, lenTest2, state2, posStateNext);
4410 + opt = &p->opt[offset];
4411 + if (curAndLenPrice < opt->price)
4413 + opt->price = curAndLenPrice;
4414 + opt->posPrev = cur + lenTest + 1;
4415 + opt->backPrev = 0;
4416 + opt->prev1IsChar = True;
4417 + opt->prev2 = True;
4418 + opt->posPrev2 = cur;
4419 + opt->backPrev2 = curBack + LZMA_NUM_REPS;
4424 + if (offs == numPairs)
4426 + curBack = matches[offs + 1];
4427 + if (curBack >= kNumFullDistances)
4428 + GetPosSlot2(curBack, posSlot);
4435 +#define ChangePair(smallDist, bigDist) (((bigDist) >> 7) > (smallDist))
4437 +static UInt32 GetOptimumFast(CLzmaEnc *p, UInt32 *backRes)
4439 + UInt32 numAvail, mainLen, mainDist, numPairs, repIndex, repLen, i;
4441 + const UInt32 *matches;
4443 + if (p->additionalOffset == 0)
4444 + mainLen = ReadMatchDistances(p, &numPairs);
4447 + mainLen = p->longestMatchLength;
4448 + numPairs = p->numPairs;
4451 + numAvail = p->numAvail;
4452 + *backRes = (UInt32)-1;
4455 + if (numAvail > LZMA_MATCH_LEN_MAX)
4456 + numAvail = LZMA_MATCH_LEN_MAX;
4457 + data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - 1;
4459 + repLen = repIndex = 0;
4460 + for (i = 0; i < LZMA_NUM_REPS; i++)
4463 + const Byte *data2 = data - (p->reps[i] + 1);
4464 + if (data[0] != data2[0] || data[1] != data2[1])
4466 + for (len = 2; len < numAvail && data[len] == data2[len]; len++);
4467 + if (len >= p->numFastBytes)
4470 + MovePos(p, len - 1);
4480 + matches = p->matches;
4481 + if (mainLen >= p->numFastBytes)
4483 + *backRes = matches[numPairs - 1] + LZMA_NUM_REPS;
4484 + MovePos(p, mainLen - 1);
4488 + mainDist = 0; /* for GCC */
4491 + mainDist = matches[numPairs - 1];
4492 + while (numPairs > 2 && mainLen == matches[numPairs - 4] + 1)
4494 + if (!ChangePair(matches[numPairs - 3], mainDist))
4497 + mainLen = matches[numPairs - 2];
4498 + mainDist = matches[numPairs - 1];
4500 + if (mainLen == 2 && mainDist >= 0x80)
4504 + if (repLen >= 2 && (
4505 + (repLen + 1 >= mainLen) ||
4506 + (repLen + 2 >= mainLen && mainDist >= (1 << 9)) ||
4507 + (repLen + 3 >= mainLen && mainDist >= (1 << 15))))
4509 + *backRes = repIndex;
4510 + MovePos(p, repLen - 1);
4514 + if (mainLen < 2 || numAvail <= 2)
4517 + p->longestMatchLength = ReadMatchDistances(p, &p->numPairs);
4518 + if (p->longestMatchLength >= 2)
4520 + UInt32 newDistance = matches[p->numPairs - 1];
4521 + if ((p->longestMatchLength >= mainLen && newDistance < mainDist) ||
4522 + (p->longestMatchLength == mainLen + 1 && !ChangePair(mainDist, newDistance)) ||
4523 + (p->longestMatchLength > mainLen + 1) ||
4524 + (p->longestMatchLength + 1 >= mainLen && mainLen >= 3 && ChangePair(newDistance, mainDist)))
4528 + data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - 1;
4529 + for (i = 0; i < LZMA_NUM_REPS; i++)
4531 + UInt32 len, limit;
4532 + const Byte *data2 = data - (p->reps[i] + 1);
4533 + if (data[0] != data2[0] || data[1] != data2[1])
4535 + limit = mainLen - 1;
4536 + for (len = 2; len < limit && data[len] == data2[len]; len++);
4540 + *backRes = mainDist + LZMA_NUM_REPS;
4541 + MovePos(p, mainLen - 2);
4545 +static void WriteEndMarker(CLzmaEnc *p, UInt32 posState)
4548 + RangeEnc_EncodeBit(&p->rc, &p->isMatch[p->state][posState], 1);
4549 + RangeEnc_EncodeBit(&p->rc, &p->isRep[p->state], 0);
4550 + p->state = kMatchNextStates[p->state];
4551 + len = LZMA_MATCH_LEN_MIN;
4552 + LenEnc_Encode2(&p->lenEnc, &p->rc, len - LZMA_MATCH_LEN_MIN, posState, !p->fastMode, p->ProbPrices);
4553 + RcTree_Encode(&p->rc, p->posSlotEncoder[GetLenToPosState(len)], kNumPosSlotBits, (1 << kNumPosSlotBits) - 1);
4554 + RangeEnc_EncodeDirectBits(&p->rc, (((UInt32)1 << 30) - 1) >> kNumAlignBits, 30 - kNumAlignBits);
4555 + RcTree_ReverseEncode(&p->rc, p->posAlignEncoder, kNumAlignBits, kAlignMask);
4558 +static SRes CheckErrors(CLzmaEnc *p)
4560 + if (p->result != SZ_OK)
4562 + if (p->rc.res != SZ_OK)
4563 + p->result = SZ_ERROR_WRITE;
4564 + if (p->matchFinderBase.result != SZ_OK)
4565 + p->result = SZ_ERROR_READ;
4566 + if (p->result != SZ_OK)
4567 + p->finished = True;
4571 +static SRes Flush(CLzmaEnc *p, UInt32 nowPos)
4573 + /* ReleaseMFStream(); */
4574 + p->finished = True;
4575 + if (p->writeEndMark)
4576 + WriteEndMarker(p, nowPos & p->pbMask);
4577 + RangeEnc_FlushData(&p->rc);
4578 + RangeEnc_FlushStream(&p->rc);
4579 + return CheckErrors(p);
4582 +static void FillAlignPrices(CLzmaEnc *p)
4585 + for (i = 0; i < kAlignTableSize; i++)
4586 + p->alignPrices[i] = RcTree_ReverseGetPrice(p->posAlignEncoder, kNumAlignBits, i, p->ProbPrices);
4587 + p->alignPriceCount = 0;
4590 +static void FillDistancesPrices(CLzmaEnc *p)
4592 + UInt32 tempPrices[kNumFullDistances];
4593 + UInt32 i, lenToPosState;
4594 + for (i = kStartPosModelIndex; i < kNumFullDistances; i++)
4596 + UInt32 posSlot = GetPosSlot1(i);
4597 + UInt32 footerBits = ((posSlot >> 1) - 1);
4598 + UInt32 base = ((2 | (posSlot & 1)) << footerBits);
4599 + tempPrices[i] = RcTree_ReverseGetPrice(p->posEncoders + base - posSlot - 1, footerBits, i - base, p->ProbPrices);
4602 + for (lenToPosState = 0; lenToPosState < kNumLenToPosStates; lenToPosState++)
4605 + const CLzmaProb *encoder = p->posSlotEncoder[lenToPosState];
4606 + UInt32 *posSlotPrices = p->posSlotPrices[lenToPosState];
4607 + for (posSlot = 0; posSlot < p->distTableSize; posSlot++)
4608 + posSlotPrices[posSlot] = RcTree_GetPrice(encoder, kNumPosSlotBits, posSlot, p->ProbPrices);
4609 + for (posSlot = kEndPosModelIndex; posSlot < p->distTableSize; posSlot++)
4610 + posSlotPrices[posSlot] += ((((posSlot >> 1) - 1) - kNumAlignBits) << kNumBitPriceShiftBits);
4613 + UInt32 *distancesPrices = p->distancesPrices[lenToPosState];
4615 + for (i = 0; i < kStartPosModelIndex; i++)
4616 + distancesPrices[i] = posSlotPrices[i];
4617 + for (; i < kNumFullDistances; i++)
4618 + distancesPrices[i] = posSlotPrices[GetPosSlot1(i)] + tempPrices[i];
4621 + p->matchPriceCount = 0;
4624 +void LzmaEnc_Construct(CLzmaEnc *p)
4626 + RangeEnc_Construct(&p->rc);
4627 + MatchFinder_Construct(&p->matchFinderBase);
4629 + MatchFinderMt_Construct(&p->matchFinderMt);
4630 + p->matchFinderMt.MatchFinder = &p->matchFinderBase;
4634 + CLzmaEncProps props;
4635 + LzmaEncProps_Init(&props);
4636 + LzmaEnc_SetProps(p, &props);
4639 + #ifndef LZMA_LOG_BSR
4640 + LzmaEnc_FastPosInit(p->g_FastPos);
4643 + LzmaEnc_InitPriceTables(p->ProbPrices);
4645 + p->saveState.litProbs = 0;
4648 +CLzmaEncHandle LzmaEnc_Create(ISzAlloc *alloc)
4651 + p = alloc->Alloc(alloc, sizeof(CLzmaEnc));
4653 + LzmaEnc_Construct((CLzmaEnc *)p);
4657 +void LzmaEnc_FreeLits(CLzmaEnc *p, ISzAlloc *alloc)
4659 + alloc->Free(alloc, p->litProbs);
4660 + alloc->Free(alloc, p->saveState.litProbs);
4662 + p->saveState.litProbs = 0;
4665 +void LzmaEnc_Destruct(CLzmaEnc *p, ISzAlloc *alloc, ISzAlloc *allocBig)
4668 + MatchFinderMt_Destruct(&p->matchFinderMt, allocBig);
4670 + MatchFinder_Free(&p->matchFinderBase, allocBig);
4671 + LzmaEnc_FreeLits(p, alloc);
4672 + RangeEnc_Free(&p->rc, alloc);
4675 +void LzmaEnc_Destroy(CLzmaEncHandle p, ISzAlloc *alloc, ISzAlloc *allocBig)
4677 + LzmaEnc_Destruct((CLzmaEnc *)p, alloc, allocBig);
4678 + alloc->Free(alloc, p);
4681 +static SRes LzmaEnc_CodeOneBlock(CLzmaEnc *p, Bool useLimits, UInt32 maxPackSize, UInt32 maxUnpackSize)
4683 + UInt32 nowPos32, startPos32;
4686 + p->matchFinder.Init(p->matchFinderObj);
4692 + RINOK(CheckErrors(p));
4694 + nowPos32 = (UInt32)p->nowPos64;
4695 + startPos32 = nowPos32;
4697 + if (p->nowPos64 == 0)
4701 + if (p->matchFinder.GetNumAvailableBytes(p->matchFinderObj) == 0)
4702 + return Flush(p, nowPos32);
4703 + ReadMatchDistances(p, &numPairs);
4704 + RangeEnc_EncodeBit(&p->rc, &p->isMatch[p->state][0], 0);
4705 + p->state = kLiteralNextStates[p->state];
4706 + curByte = p->matchFinder.GetIndexByte(p->matchFinderObj, 0 - p->additionalOffset);
4707 + LitEnc_Encode(&p->rc, p->litProbs, curByte);
4708 + p->additionalOffset--;
4712 + if (p->matchFinder.GetNumAvailableBytes(p->matchFinderObj) != 0)
4715 + UInt32 pos, len, posState;
4718 + len = GetOptimumFast(p, &pos);
4720 + len = GetOptimum(p, nowPos32, &pos);
4723 + printf("\n pos = %4X, len = %d pos = %d", nowPos32, len, pos);
4726 + posState = nowPos32 & p->pbMask;
4727 + if (len == 1 && pos == (UInt32)-1)
4733 + RangeEnc_EncodeBit(&p->rc, &p->isMatch[p->state][posState], 0);
4734 + data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - p->additionalOffset;
4736 + probs = LIT_PROBS(nowPos32, *(data - 1));
4737 + if (IsCharState(p->state))
4738 + LitEnc_Encode(&p->rc, probs, curByte);
4740 + LitEnc_EncodeMatched(&p->rc, probs, curByte, *(data - p->reps[0] - 1));
4741 + p->state = kLiteralNextStates[p->state];
4745 + RangeEnc_EncodeBit(&p->rc, &p->isMatch[p->state][posState], 1);
4746 + if (pos < LZMA_NUM_REPS)
4748 + RangeEnc_EncodeBit(&p->rc, &p->isRep[p->state], 1);
4751 + RangeEnc_EncodeBit(&p->rc, &p->isRepG0[p->state], 0);
4752 + RangeEnc_EncodeBit(&p->rc, &p->isRep0Long[p->state][posState], ((len == 1) ? 0 : 1));
4756 + UInt32 distance = p->reps[pos];
4757 + RangeEnc_EncodeBit(&p->rc, &p->isRepG0[p->state], 1);
4759 + RangeEnc_EncodeBit(&p->rc, &p->isRepG1[p->state], 0);
4762 + RangeEnc_EncodeBit(&p->rc, &p->isRepG1[p->state], 1);
4763 + RangeEnc_EncodeBit(&p->rc, &p->isRepG2[p->state], pos - 2);
4765 + p->reps[3] = p->reps[2];
4766 + p->reps[2] = p->reps[1];
4768 + p->reps[1] = p->reps[0];
4769 + p->reps[0] = distance;
4772 + p->state = kShortRepNextStates[p->state];
4775 + LenEnc_Encode2(&p->repLenEnc, &p->rc, len - LZMA_MATCH_LEN_MIN, posState, !p->fastMode, p->ProbPrices);
4776 + p->state = kRepNextStates[p->state];
4782 + RangeEnc_EncodeBit(&p->rc, &p->isRep[p->state], 0);
4783 + p->state = kMatchNextStates[p->state];
4784 + LenEnc_Encode2(&p->lenEnc, &p->rc, len - LZMA_MATCH_LEN_MIN, posState, !p->fastMode, p->ProbPrices);
4785 + pos -= LZMA_NUM_REPS;
4786 + GetPosSlot(pos, posSlot);
4787 + RcTree_Encode(&p->rc, p->posSlotEncoder[GetLenToPosState(len)], kNumPosSlotBits, posSlot);
4789 + if (posSlot >= kStartPosModelIndex)
4791 + UInt32 footerBits = ((posSlot >> 1) - 1);
4792 + UInt32 base = ((2 | (posSlot & 1)) << footerBits);
4793 + UInt32 posReduced = pos - base;
4795 + if (posSlot < kEndPosModelIndex)
4796 + RcTree_ReverseEncode(&p->rc, p->posEncoders + base - posSlot - 1, footerBits, posReduced);
4799 + RangeEnc_EncodeDirectBits(&p->rc, posReduced >> kNumAlignBits, footerBits - kNumAlignBits);
4800 + RcTree_ReverseEncode(&p->rc, p->posAlignEncoder, kNumAlignBits, posReduced & kAlignMask);
4801 + p->alignPriceCount++;
4804 + p->reps[3] = p->reps[2];
4805 + p->reps[2] = p->reps[1];
4806 + p->reps[1] = p->reps[0];
4808 + p->matchPriceCount++;
4811 + p->additionalOffset -= len;
4813 + if (p->additionalOffset == 0)
4818 + if (p->matchPriceCount >= (1 << 7))
4819 + FillDistancesPrices(p);
4820 + if (p->alignPriceCount >= kAlignTableSize)
4821 + FillAlignPrices(p);
4823 + if (p->matchFinder.GetNumAvailableBytes(p->matchFinderObj) == 0)
4825 + processed = nowPos32 - startPos32;
4828 + if (processed + kNumOpts + 300 >= maxUnpackSize ||
4829 + RangeEnc_GetProcessed(&p->rc) + kNumOpts * 2 >= maxPackSize)
4832 + else if (processed >= (1 << 15))
4834 + p->nowPos64 += nowPos32 - startPos32;
4835 + return CheckErrors(p);
4839 + p->nowPos64 += nowPos32 - startPos32;
4840 + return Flush(p, nowPos32);
4843 +#define kBigHashDicLimit ((UInt32)1 << 24)
4845 +static SRes LzmaEnc_Alloc(CLzmaEnc *p, UInt32 keepWindowSize, ISzAlloc *alloc, ISzAlloc *allocBig)
4847 + UInt32 beforeSize = kNumOpts;
4849 + if (!RangeEnc_Alloc(&p->rc, alloc))
4850 + return SZ_ERROR_MEM;
4851 + btMode = (p->matchFinderBase.btMode != 0);
4853 + p->mtMode = (p->multiThread && !p->fastMode && btMode);
4857 + unsigned lclp = p->lc + p->lp;
4858 + if (p->litProbs == 0 || p->saveState.litProbs == 0 || p->lclp != lclp)
4860 + LzmaEnc_FreeLits(p, alloc);
4861 + p->litProbs = (CLzmaProb *)alloc->Alloc(alloc, (0x300 << lclp) * sizeof(CLzmaProb));
4862 + p->saveState.litProbs = (CLzmaProb *)alloc->Alloc(alloc, (0x300 << lclp) * sizeof(CLzmaProb));
4863 + if (p->litProbs == 0 || p->saveState.litProbs == 0)
4865 + LzmaEnc_FreeLits(p, alloc);
4866 + return SZ_ERROR_MEM;
4872 + p->matchFinderBase.bigHash = (p->dictSize > kBigHashDicLimit);
4874 + if (beforeSize + p->dictSize < keepWindowSize)
4875 + beforeSize = keepWindowSize - p->dictSize;
4880 + RINOK(MatchFinderMt_Create(&p->matchFinderMt, p->dictSize, beforeSize, p->numFastBytes, LZMA_MATCH_LEN_MAX, allocBig));
4881 + p->matchFinderObj = &p->matchFinderMt;
4882 + MatchFinderMt_CreateVTable(&p->matchFinderMt, &p->matchFinder);
4887 + if (!MatchFinder_Create(&p->matchFinderBase, p->dictSize, beforeSize, p->numFastBytes, LZMA_MATCH_LEN_MAX, allocBig))
4888 + return SZ_ERROR_MEM;
4889 + p->matchFinderObj = &p->matchFinderBase;
4890 + MatchFinder_CreateVTable(&p->matchFinderBase, &p->matchFinder);
4895 +void LzmaEnc_Init(CLzmaEnc *p)
4899 + for (i = 0 ; i < LZMA_NUM_REPS; i++)
4902 + RangeEnc_Init(&p->rc);
4905 + for (i = 0; i < kNumStates; i++)
4908 + for (j = 0; j < LZMA_NUM_PB_STATES_MAX; j++)
4910 + p->isMatch[i][j] = kProbInitValue;
4911 + p->isRep0Long[i][j] = kProbInitValue;
4913 + p->isRep[i] = kProbInitValue;
4914 + p->isRepG0[i] = kProbInitValue;
4915 + p->isRepG1[i] = kProbInitValue;
4916 + p->isRepG2[i] = kProbInitValue;
4920 + UInt32 num = 0x300 << (p->lp + p->lc);
4921 + for (i = 0; i < num; i++)
4922 + p->litProbs[i] = kProbInitValue;
4926 + for (i = 0; i < kNumLenToPosStates; i++)
4928 + CLzmaProb *probs = p->posSlotEncoder[i];
4930 + for (j = 0; j < (1 << kNumPosSlotBits); j++)
4931 + probs[j] = kProbInitValue;
4935 + for (i = 0; i < kNumFullDistances - kEndPosModelIndex; i++)
4936 + p->posEncoders[i] = kProbInitValue;
4939 + LenEnc_Init(&p->lenEnc.p);
4940 + LenEnc_Init(&p->repLenEnc.p);
4942 + for (i = 0; i < (1 << kNumAlignBits); i++)
4943 + p->posAlignEncoder[i] = kProbInitValue;
4945 + p->optimumEndIndex = 0;
4946 + p->optimumCurrentIndex = 0;
4947 + p->additionalOffset = 0;
4949 + p->pbMask = (1 << p->pb) - 1;
4950 + p->lpMask = (1 << p->lp) - 1;
4953 +void LzmaEnc_InitPrices(CLzmaEnc *p)
4957 + FillDistancesPrices(p);
4958 + FillAlignPrices(p);
4961 + p->lenEnc.tableSize =
4962 + p->repLenEnc.tableSize =
4963 + p->numFastBytes + 1 - LZMA_MATCH_LEN_MIN;
4964 + LenPriceEnc_UpdateTables(&p->lenEnc, 1 << p->pb, p->ProbPrices);
4965 + LenPriceEnc_UpdateTables(&p->repLenEnc, 1 << p->pb, p->ProbPrices);
4968 +static SRes LzmaEnc_AllocAndInit(CLzmaEnc *p, UInt32 keepWindowSize, ISzAlloc *alloc, ISzAlloc *allocBig)
4971 + for (i = 0; i < (UInt32)kDicLogSizeMaxCompress; i++)
4972 + if (p->dictSize <= ((UInt32)1 << i))
4974 + p->distTableSize = i * 2;
4976 + p->finished = False;
4977 + p->result = SZ_OK;
4978 + RINOK(LzmaEnc_Alloc(p, keepWindowSize, alloc, allocBig));
4980 + LzmaEnc_InitPrices(p);
4985 +static SRes LzmaEnc_Prepare(CLzmaEncHandle pp, ISeqOutStream *outStream, ISeqInStream *inStream,
4986 + ISzAlloc *alloc, ISzAlloc *allocBig)
4988 + CLzmaEnc *p = (CLzmaEnc *)pp;
4989 + p->matchFinderBase.stream = inStream;
4991 + p->rc.outStream = outStream;
4992 + return LzmaEnc_AllocAndInit(p, 0, alloc, allocBig);
4995 +SRes LzmaEnc_PrepareForLzma2(CLzmaEncHandle pp,
4996 + ISeqInStream *inStream, UInt32 keepWindowSize,
4997 + ISzAlloc *alloc, ISzAlloc *allocBig)
4999 + CLzmaEnc *p = (CLzmaEnc *)pp;
5000 + p->matchFinderBase.stream = inStream;
5002 + return LzmaEnc_AllocAndInit(p, keepWindowSize, alloc, allocBig);
5005 +static void LzmaEnc_SetInputBuf(CLzmaEnc *p, const Byte *src, SizeT srcLen)
5007 + p->matchFinderBase.directInput = 1;
5008 + p->matchFinderBase.bufferBase = (Byte *)src;
5009 + p->matchFinderBase.directInputRem = srcLen;
5012 +SRes LzmaEnc_MemPrepare(CLzmaEncHandle pp, const Byte *src, SizeT srcLen,
5013 + UInt32 keepWindowSize, ISzAlloc *alloc, ISzAlloc *allocBig)
5015 + CLzmaEnc *p = (CLzmaEnc *)pp;
5016 + LzmaEnc_SetInputBuf(p, src, srcLen);
5019 + return LzmaEnc_AllocAndInit(p, keepWindowSize, alloc, allocBig);
5022 +void LzmaEnc_Finish(CLzmaEncHandle pp)
5025 + CLzmaEnc *p = (CLzmaEnc *)pp;
5027 + MatchFinderMt_ReleaseStream(&p->matchFinderMt);
5035 + ISeqOutStream funcTable;
5039 +} CSeqOutStreamBuf;
5041 +static size_t MyWrite(void *pp, const void *data, size_t size)
5043 + CSeqOutStreamBuf *p = (CSeqOutStreamBuf *)pp;
5044 + if (p->rem < size)
5047 + p->overflow = True;
5049 + memcpy(p->data, data, size);
5056 +UInt32 LzmaEnc_GetNumAvailableBytes(CLzmaEncHandle pp)
5058 + const CLzmaEnc *p = (CLzmaEnc *)pp;
5059 + return p->matchFinder.GetNumAvailableBytes(p->matchFinderObj);
5062 +const Byte *LzmaEnc_GetCurBuf(CLzmaEncHandle pp)
5064 + const CLzmaEnc *p = (CLzmaEnc *)pp;
5065 + return p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - p->additionalOffset;
5068 +SRes LzmaEnc_CodeOneMemBlock(CLzmaEncHandle pp, Bool reInit,
5069 + Byte *dest, size_t *destLen, UInt32 desiredPackSize, UInt32 *unpackSize)
5071 + CLzmaEnc *p = (CLzmaEnc *)pp;
5074 + CSeqOutStreamBuf outStream;
5076 + outStream.funcTable.Write = MyWrite;
5077 + outStream.data = dest;
5078 + outStream.rem = *destLen;
5079 + outStream.overflow = False;
5081 + p->writeEndMark = False;
5082 + p->finished = False;
5083 + p->result = SZ_OK;
5087 + LzmaEnc_InitPrices(p);
5088 + nowPos64 = p->nowPos64;
5089 + RangeEnc_Init(&p->rc);
5090 + p->rc.outStream = &outStream.funcTable;
5092 + res = LzmaEnc_CodeOneBlock(p, True, desiredPackSize, *unpackSize);
5094 + *unpackSize = (UInt32)(p->nowPos64 - nowPos64);
5095 + *destLen -= outStream.rem;
5096 + if (outStream.overflow)
5097 + return SZ_ERROR_OUTPUT_EOF;
5102 +static SRes LzmaEnc_Encode2(CLzmaEnc *p, ICompressProgress *progress)
5107 + Byte allocaDummy[0x300];
5109 + for (i = 0; i < 16; i++)
5110 + allocaDummy[i] = (Byte)i;
5115 + res = LzmaEnc_CodeOneBlock(p, False, 0, 0);
5116 + if (res != SZ_OK || p->finished != 0)
5118 + if (progress != 0)
5120 + res = progress->Progress(progress, p->nowPos64, RangeEnc_GetProcessed(&p->rc));
5123 + res = SZ_ERROR_PROGRESS;
5128 + LzmaEnc_Finish(p);
5132 +SRes LzmaEnc_Encode(CLzmaEncHandle pp, ISeqOutStream *outStream, ISeqInStream *inStream, ICompressProgress *progress,
5133 + ISzAlloc *alloc, ISzAlloc *allocBig)
5135 + RINOK(LzmaEnc_Prepare(pp, outStream, inStream, alloc, allocBig));
5136 + return LzmaEnc_Encode2((CLzmaEnc *)pp, progress);
5139 +SRes LzmaEnc_WriteProperties(CLzmaEncHandle pp, Byte *props, SizeT *size)
5141 + CLzmaEnc *p = (CLzmaEnc *)pp;
5143 + UInt32 dictSize = p->dictSize;
5144 + if (*size < LZMA_PROPS_SIZE)
5145 + return SZ_ERROR_PARAM;
5146 + *size = LZMA_PROPS_SIZE;
5147 + props[0] = (Byte)((p->pb * 5 + p->lp) * 9 + p->lc);
5149 + for (i = 11; i <= 30; i++)
5151 + if (dictSize <= ((UInt32)2 << i))
5153 + dictSize = (2 << i);
5156 + if (dictSize <= ((UInt32)3 << i))
5158 + dictSize = (3 << i);
5163 + for (i = 0; i < 4; i++)
5164 + props[1 + i] = (Byte)(dictSize >> (8 * i));
5168 +SRes LzmaEnc_MemEncode(CLzmaEncHandle pp, Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen,
5169 + int writeEndMark, ICompressProgress *progress, ISzAlloc *alloc, ISzAlloc *allocBig)
5172 + CLzmaEnc *p = (CLzmaEnc *)pp;
5174 + CSeqOutStreamBuf outStream;
5176 + LzmaEnc_SetInputBuf(p, src, srcLen);
5178 + outStream.funcTable.Write = MyWrite;
5179 + outStream.data = dest;
5180 + outStream.rem = *destLen;
5181 + outStream.overflow = False;
5183 + p->writeEndMark = writeEndMark;
5185 + p->rc.outStream = &outStream.funcTable;
5186 + res = LzmaEnc_MemPrepare(pp, src, srcLen, 0, alloc, allocBig);
5188 + res = LzmaEnc_Encode2(p, progress);
5190 + *destLen -= outStream.rem;
5191 + if (outStream.overflow)
5192 + return SZ_ERROR_OUTPUT_EOF;
5196 +SRes LzmaEncode(Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen,
5197 + const CLzmaEncProps *props, Byte *propsEncoded, SizeT *propsSize, int writeEndMark,
5198 + ICompressProgress *progress, ISzAlloc *alloc, ISzAlloc *allocBig)
5200 + CLzmaEnc *p = (CLzmaEnc *)LzmaEnc_Create(alloc);
5203 + return SZ_ERROR_MEM;
5205 + res = LzmaEnc_SetProps(p, props);
5208 + res = LzmaEnc_WriteProperties(p, propsEncoded, propsSize);
5210 + res = LzmaEnc_MemEncode(p, dest, destLen, src, srcLen,
5211 + writeEndMark, progress, alloc, allocBig);
5214 + LzmaEnc_Destroy(p, alloc, allocBig);
5217 diff --git a/lib/lzma/Makefile b/lib/lzma/Makefile
5218 new file mode 100644
5219 index 000000000000..02e799c99381
5221 +++ b/lib/lzma/Makefile
5223 +lzma_compress-objs := LzFind.o LzmaEnc.o
5224 +lzma_decompress-objs := LzmaDec.o
5226 +obj-$(CONFIG_LZMA_COMPRESS) += lzma_compress.o
5227 +obj-$(CONFIG_LZMA_DECOMPRESS) += lzma_decompress.o
5229 +EXTRA_CFLAGS += -Iinclude/linux -Iinclude/linux/lzma -include types.h