1 --- a/jffsX-utils/Makemodule.am
2 +++ b/jffsX-utils/Makemodule.am
3 @@ -4,7 +4,10 @@ mkfs_jffs2_SOURCES = \
4 jffsX-utils/compr_zlib.c \
7 - jffsX-utils/compr_lzo.c \
8 + jffsX-utils/compr_lzma.c \
9 + jffsX-utils/lzma/LzFind.c \
10 + jffsX-utils/lzma/LzmaEnc.c \
11 + jffsX-utils/lzma/LzmaDec.c \
13 jffsX-utils/compr_rtime.c \
15 @@ -12,8 +15,13 @@ mkfs_jffs2_SOURCES = \
16 jffsX-utils/summary.h \
17 include/linux/jffs2.h \
18 include/mtd/jffs2-user.h
21 +mkfs_jffs2_SOURCES += jffsX-utils/compr_lzo.c
24 mkfs_jffs2_LDADD = libmtd.a $(ZLIB_LIBS) $(LZO_LIBS)
25 -mkfs_jffs2_CPPFLAGS = $(AM_CPPFLAGS) $(ZLIB_CFLAGS) $(LZO_CFLAGS)
26 +mkfs_jffs2_CPPFLAGS = $(AM_CPPFLAGS) $(ZLIB_CFLAGS) $(LZO_CFLAGS) -I./include/linux/lzma
28 jffs2reader_SOURCES = jffsX-utils/jffs2reader.c include/mtd/jffs2-user.h
29 jffs2reader_LDADD = libmtd.a $(ZLIB_LIBS) $(LZO_LIBS)
30 --- a/jffsX-utils/compr.c
31 +++ b/jffsX-utils/compr.c
32 @@ -520,6 +520,9 @@ int jffs2_compressors_init(void)
33 #ifdef CONFIG_JFFS2_LZO
36 +#ifdef CONFIG_JFFS2_LZMA
42 @@ -534,5 +537,8 @@ int jffs2_compressors_exit(void)
43 #ifdef CONFIG_JFFS2_LZO
46 +#ifdef CONFIG_JFFS2_LZMA
51 --- a/jffsX-utils/compr.h
52 +++ b/jffsX-utils/compr.h
55 #define CONFIG_JFFS2_ZLIB
56 #define CONFIG_JFFS2_RTIME
57 -#define CONFIG_JFFS2_LZO
58 +#define CONFIG_JFFS2_LZMA
60 #define JFFS2_RUBINMIPS_PRIORITY 10
61 #define JFFS2_DYNRUBIN_PRIORITY 20
62 #define JFFS2_RTIME_PRIORITY 50
63 -#define JFFS2_ZLIB_PRIORITY 60
64 -#define JFFS2_LZO_PRIORITY 80
65 +#define JFFS2_LZMA_PRIORITY 70
66 +#define JFFS2_ZLIB_PRIORITY 80
67 +#define JFFS2_LZO_PRIORITY 90
69 #define JFFS2_COMPR_MODE_NONE 0
70 #define JFFS2_COMPR_MODE_PRIORITY 1
71 @@ -115,5 +116,10 @@ void jffs2_rtime_exit(void);
72 int jffs2_lzo_init(void);
73 void jffs2_lzo_exit(void);
75 +#ifdef CONFIG_JFFS2_LZMA
76 +int jffs2_lzma_init(void);
77 +void jffs2_lzma_exit(void);
81 #endif /* __JFFS2_COMPR_H__ */
83 +++ b/jffsX-utils/compr_lzma.c
86 + * JFFS2 -- Journalling Flash File System, Version 2.
88 + * For licensing information, see the file 'LICENCE' in this directory.
90 + * JFFS2 wrapper to the LZMA C SDK
94 +#include <linux/lzma.h>
98 + static DEFINE_MUTEX(deflate_mutex);
102 +Byte propsEncoded[LZMA_PROPS_SIZE];
103 +SizeT propsSize = sizeof(propsEncoded);
105 +STATIC void lzma_free_workspace(void)
107 + LzmaEnc_Destroy(p, &lzma_alloc, &lzma_alloc);
110 +STATIC int INIT lzma_alloc_workspace(CLzmaEncProps *props)
112 + if ((p = (CLzmaEncHandle *)LzmaEnc_Create(&lzma_alloc)) == NULL)
114 + PRINT_ERROR("Failed to allocate lzma deflate workspace\n");
118 + if (LzmaEnc_SetProps(p, props) != SZ_OK)
120 + lzma_free_workspace();
124 + if (LzmaEnc_WriteProperties(p, propsEncoded, &propsSize) != SZ_OK)
126 + lzma_free_workspace();
133 +STATIC int jffs2_lzma_compress(unsigned char *data_in, unsigned char *cpage_out,
134 + uint32_t *sourcelen, uint32_t *dstlen)
136 + SizeT compress_size = (SizeT)(*dstlen);
140 + mutex_lock(&deflate_mutex);
143 + ret = LzmaEnc_MemEncode(p, cpage_out, &compress_size, data_in, *sourcelen,
144 + 0, NULL, &lzma_alloc, &lzma_alloc);
147 + mutex_unlock(&deflate_mutex);
153 + *dstlen = (uint32_t)compress_size;
158 +STATIC int jffs2_lzma_decompress(unsigned char *data_in, unsigned char *cpage_out,
159 + uint32_t srclen, uint32_t destlen)
162 + SizeT dl = (SizeT)destlen;
163 + SizeT sl = (SizeT)srclen;
164 + ELzmaStatus status;
166 + ret = LzmaDecode(cpage_out, &dl, data_in, &sl, propsEncoded,
167 + propsSize, LZMA_FINISH_ANY, &status, &lzma_alloc);
169 + if (ret != SZ_OK || status == LZMA_STATUS_NOT_FINISHED || dl != (SizeT)destlen)
175 +static struct jffs2_compressor jffs2_lzma_comp = {
176 + .priority = JFFS2_LZMA_PRIORITY,
178 + .compr = JFFS2_COMPR_LZMA,
179 + .compress = &jffs2_lzma_compress,
180 + .decompress = &jffs2_lzma_decompress,
184 +int INIT jffs2_lzma_init(void)
187 + CLzmaEncProps props;
188 + LzmaEncProps_Init(&props);
190 + props.dictSize = LZMA_BEST_DICT(0x2000);
191 + props.level = LZMA_BEST_LEVEL;
192 + props.lc = LZMA_BEST_LC;
193 + props.lp = LZMA_BEST_LP;
194 + props.pb = LZMA_BEST_PB;
195 + props.fb = LZMA_BEST_FB;
197 + ret = lzma_alloc_workspace(&props);
201 + ret = jffs2_register_compressor(&jffs2_lzma_comp);
203 + lzma_free_workspace();
208 +void jffs2_lzma_exit(void)
210 + jffs2_unregister_compressor(&jffs2_lzma_comp);
211 + lzma_free_workspace();
213 --- a/include/linux/jffs2.h
214 +++ b/include/linux/jffs2.h
216 #define JFFS2_COMPR_DYNRUBIN 0x05
217 #define JFFS2_COMPR_ZLIB 0x06
218 #define JFFS2_COMPR_LZO 0x07
219 +#define JFFS2_COMPR_LZMA 0x08
220 /* Compatibility flags. */
221 #define JFFS2_COMPAT_MASK 0xc000 /* What do to if an unknown nodetype is found */
222 #define JFFS2_NODE_ACCURATE 0x2000
224 +++ b/include/linux/lzma.h
230 + #include <linux/kernel.h>
231 + #include <linux/sched.h>
232 + #include <linux/slab.h>
233 + #include <linux/vmalloc.h>
234 + #include <linux/init.h>
235 + #define LZMA_MALLOC vmalloc
236 + #define LZMA_FREE vfree
237 + #define PRINT_ERROR(msg) printk(KERN_WARNING #msg)
238 + #define INIT __init
239 + #define STATIC static
241 + #include <stdint.h>
242 + #include <stdlib.h>
244 + #include <unistd.h>
245 + #include <string.h>
247 + #include <linux/jffs2.h>
249 + extern int page_size;
250 + #define PAGE_SIZE page_size
252 + #define LZMA_MALLOC malloc
253 + #define LZMA_FREE free
254 + #define PRINT_ERROR(msg) fprintf(stderr, msg)
256 + #define STATIC static
259 +#include "lzma/LzmaDec.h"
260 +#include "lzma/LzmaEnc.h"
262 +#define LZMA_BEST_LEVEL (9)
263 +#define LZMA_BEST_LC (0)
264 +#define LZMA_BEST_LP (0)
265 +#define LZMA_BEST_PB (0)
266 +#define LZMA_BEST_FB (273)
268 +#define LZMA_BEST_DICT(n) (((int)((n) / 2)) * 2)
270 +static void *p_lzma_malloc(void *p, size_t size)
275 + return LZMA_MALLOC(size);
278 +static void p_lzma_free(void *p, void *address)
280 + if (address != NULL)
281 + LZMA_FREE(address);
284 +static ISzAlloc lzma_alloc = {p_lzma_malloc, p_lzma_free};
288 +++ b/include/linux/lzma/LzFind.h
290 +/* LzFind.h -- Match finder for LZ algorithms
292 +Copyright (c) 1999-2008 Igor Pavlov
293 +You can use any of the following license options:
294 + 1) GNU Lesser General Public License (GNU LGPL)
295 + 2) Common Public License (CPL)
296 + 3) Common Development and Distribution License (CDDL) Version 1.0
297 + 4) Igor Pavlov, as the author of this code, expressly permits you to
298 + statically or dynamically link your code (or bind by name) to this file,
299 + while you keep this file unmodified.
307 +typedef UInt32 CLzRef;
309 +typedef struct _CMatchFinder
317 + UInt32 cyclicBufferPos;
318 + UInt32 cyclicBufferSize; /* it must be = (historySize + 1) */
320 + UInt32 matchMaxLen;
327 + ISeqInStream *stream;
328 + int streamEndWasReached;
331 + UInt32 keepSizeBefore;
332 + UInt32 keepSizeAfter;
334 + UInt32 numHashBytes;
337 + /* int skipModeBits; */
339 + UInt32 historySize;
340 + UInt32 fixedHashSize;
341 + UInt32 hashSizeSum;
347 +#define Inline_MatchFinder_GetPointerToCurrentPos(p) ((p)->buffer)
348 +#define Inline_MatchFinder_GetIndexByte(p, index) ((p)->buffer[(Int32)(index)])
350 +#define Inline_MatchFinder_GetNumAvailableBytes(p) ((p)->streamPos - (p)->pos)
352 +int MatchFinder_NeedMove(CMatchFinder *p);
353 +Byte *MatchFinder_GetPointerToCurrentPos(CMatchFinder *p);
354 +void MatchFinder_MoveBlock(CMatchFinder *p);
355 +void MatchFinder_ReadIfRequired(CMatchFinder *p);
357 +void MatchFinder_Construct(CMatchFinder *p);
360 + historySize <= 3 GB
361 + keepAddBufferBefore + matchMaxLen + keepAddBufferAfter < 511MB
363 +int MatchFinder_Create(CMatchFinder *p, UInt32 historySize,
364 + UInt32 keepAddBufferBefore, UInt32 matchMaxLen, UInt32 keepAddBufferAfter,
366 +void MatchFinder_Free(CMatchFinder *p, ISzAlloc *alloc);
367 +void MatchFinder_Normalize3(UInt32 subValue, CLzRef *items, UInt32 numItems);
368 +void MatchFinder_ReduceOffsets(CMatchFinder *p, UInt32 subValue);
370 +UInt32 * GetMatchesSpec1(UInt32 lenLimit, UInt32 curMatch, UInt32 pos, const Byte *buffer, CLzRef *son,
371 + UInt32 _cyclicBufferPos, UInt32 _cyclicBufferSize, UInt32 _cutValue,
372 + UInt32 *distances, UInt32 maxLen);
376 + Mf_GetNumAvailableBytes_Func must be called before each Mf_GetMatchLen_Func.
377 + Mf_GetPointerToCurrentPos_Func's result must be used only before any other function
380 +typedef void (*Mf_Init_Func)(void *object);
381 +typedef Byte (*Mf_GetIndexByte_Func)(void *object, Int32 index);
382 +typedef UInt32 (*Mf_GetNumAvailableBytes_Func)(void *object);
383 +typedef const Byte * (*Mf_GetPointerToCurrentPos_Func)(void *object);
384 +typedef UInt32 (*Mf_GetMatches_Func)(void *object, UInt32 *distances);
385 +typedef void (*Mf_Skip_Func)(void *object, UInt32);
387 +typedef struct _IMatchFinder
390 + Mf_GetIndexByte_Func GetIndexByte;
391 + Mf_GetNumAvailableBytes_Func GetNumAvailableBytes;
392 + Mf_GetPointerToCurrentPos_Func GetPointerToCurrentPos;
393 + Mf_GetMatches_Func GetMatches;
397 +void MatchFinder_CreateVTable(CMatchFinder *p, IMatchFinder *vTable);
399 +void MatchFinder_Init(CMatchFinder *p);
400 +UInt32 Bt3Zip_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances);
401 +UInt32 Hc3Zip_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances);
402 +void Bt3Zip_MatchFinder_Skip(CMatchFinder *p, UInt32 num);
403 +void Hc3Zip_MatchFinder_Skip(CMatchFinder *p, UInt32 num);
407 +++ b/include/linux/lzma/LzHash.h
409 +/* LzHash.h -- HASH functions for LZ algorithms
411 +Copyright (c) 1999-2008 Igor Pavlov
412 +Read LzFind.h for license options */
417 +#define kHash2Size (1 << 10)
418 +#define kHash3Size (1 << 16)
419 +#define kHash4Size (1 << 20)
421 +#define kFix3HashSize (kHash2Size)
422 +#define kFix4HashSize (kHash2Size + kHash3Size)
423 +#define kFix5HashSize (kHash2Size + kHash3Size + kHash4Size)
425 +#define HASH2_CALC hashValue = cur[0] | ((UInt32)cur[1] << 8);
427 +#define HASH3_CALC { \
428 + UInt32 temp = p->crc[cur[0]] ^ cur[1]; \
429 + hash2Value = temp & (kHash2Size - 1); \
430 + hashValue = (temp ^ ((UInt32)cur[2] << 8)) & p->hashMask; }
432 +#define HASH4_CALC { \
433 + UInt32 temp = p->crc[cur[0]] ^ cur[1]; \
434 + hash2Value = temp & (kHash2Size - 1); \
435 + hash3Value = (temp ^ ((UInt32)cur[2] << 8)) & (kHash3Size - 1); \
436 + hashValue = (temp ^ ((UInt32)cur[2] << 8) ^ (p->crc[cur[3]] << 5)) & p->hashMask; }
438 +#define HASH5_CALC { \
439 + UInt32 temp = p->crc[cur[0]] ^ cur[1]; \
440 + hash2Value = temp & (kHash2Size - 1); \
441 + hash3Value = (temp ^ ((UInt32)cur[2] << 8)) & (kHash3Size - 1); \
442 + hash4Value = (temp ^ ((UInt32)cur[2] << 8) ^ (p->crc[cur[3]] << 5)); \
443 + hashValue = (hash4Value ^ (p->crc[cur[4]] << 3)) & p->hashMask; \
444 + hash4Value &= (kHash4Size - 1); }
446 +/* #define HASH_ZIP_CALC hashValue = ((cur[0] | ((UInt32)cur[1] << 8)) ^ p->crc[cur[2]]) & 0xFFFF; */
447 +#define HASH_ZIP_CALC hashValue = ((cur[2] | ((UInt32)cur[0] << 8)) ^ p->crc[cur[1]]) & 0xFFFF;
450 +#define MT_HASH2_CALC \
451 + hash2Value = (p->crc[cur[0]] ^ cur[1]) & (kHash2Size - 1);
453 +#define MT_HASH3_CALC { \
454 + UInt32 temp = p->crc[cur[0]] ^ cur[1]; \
455 + hash2Value = temp & (kHash2Size - 1); \
456 + hash3Value = (temp ^ ((UInt32)cur[2] << 8)) & (kHash3Size - 1); }
458 +#define MT_HASH4_CALC { \
459 + UInt32 temp = p->crc[cur[0]] ^ cur[1]; \
460 + hash2Value = temp & (kHash2Size - 1); \
461 + hash3Value = (temp ^ ((UInt32)cur[2] << 8)) & (kHash3Size - 1); \
462 + hash4Value = (temp ^ ((UInt32)cur[2] << 8) ^ (p->crc[cur[3]] << 5)) & (kHash4Size - 1); }
466 +++ b/include/linux/lzma/LzmaDec.h
468 +/* LzmaDec.h -- LZMA Decoder
470 +Copyright (c) 1999-2008 Igor Pavlov
471 +You can use any of the following license options:
472 + 1) GNU Lesser General Public License (GNU LGPL)
473 + 2) Common Public License (CPL)
474 + 3) Common Development and Distribution License (CDDL) Version 1.0
475 + 4) Igor Pavlov, as the author of this code, expressly permits you to
476 + statically or dynamically link your code (or bind by name) to this file,
477 + while you keep this file unmodified.
485 +/* #define _LZMA_PROB32 */
486 +/* _LZMA_PROB32 can increase the speed on some CPUs,
487 + but memory usage for CLzmaDec::probs will be doubled in that case */
490 +#define CLzmaProb UInt32
492 +#define CLzmaProb UInt16
496 +/* ---------- LZMA Properties ---------- */
498 +#define LZMA_PROPS_SIZE 5
500 +typedef struct _CLzmaProps
502 + unsigned lc, lp, pb;
506 +/* LzmaProps_Decode - decodes properties
509 + SZ_ERROR_UNSUPPORTED - Unsupported properties
512 +SRes LzmaProps_Decode(CLzmaProps *p, const Byte *data, unsigned size);
515 +/* ---------- LZMA Decoder state ---------- */
517 +/* LZMA_REQUIRED_INPUT_MAX = number of required input bytes for worst case.
518 + Num bits = log2((2^11 / 31) ^ 22) + 26 < 134 + 26 = 160; */
520 +#define LZMA_REQUIRED_INPUT_MAX 20
528 + UInt32 range, code;
531 + UInt32 processedPos;
532 + UInt32 checkDicSize;
535 + unsigned remainLen;
539 + unsigned tempBufSize;
540 + Byte tempBuf[LZMA_REQUIRED_INPUT_MAX];
543 +#define LzmaDec_Construct(p) { (p)->dic = 0; (p)->probs = 0; }
545 +void LzmaDec_Init(CLzmaDec *p);
547 +/* There are two types of LZMA streams:
548 + 0) Stream with end mark. That end mark adds about 6 bytes to compressed size.
549 + 1) Stream without end mark. You must know exact uncompressed size to decompress such stream. */
553 + LZMA_FINISH_ANY, /* finish at any point */
554 + LZMA_FINISH_END /* block must be finished at the end */
557 +/* ELzmaFinishMode has meaning only if the decoding reaches output limit !!!
559 + You must use LZMA_FINISH_END, when you know that current output buffer
560 + covers last bytes of block. In other cases you must use LZMA_FINISH_ANY.
562 + If LZMA decoder sees end marker before reaching output limit, it returns SZ_OK,
563 + and output value of destLen will be less than output buffer size limit.
564 + You can check status result also.
566 + You can use multiple checks to test data integrity after full decompression:
567 + 1) Check Result and "status" variable.
568 + 2) Check that output(destLen) = uncompressedSize, if you know real uncompressedSize.
569 + 3) Check that output(srcLen) = compressedSize, if you know real compressedSize.
570 + You must use correct finish mode in that case. */
574 + LZMA_STATUS_NOT_SPECIFIED, /* use main error code instead */
575 + LZMA_STATUS_FINISHED_WITH_MARK, /* stream was finished with end mark. */
576 + LZMA_STATUS_NOT_FINISHED, /* stream was not finished */
577 + LZMA_STATUS_NEEDS_MORE_INPUT, /* you must provide more input bytes */
578 + LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK /* there is probability that stream was finished without end mark */
581 +/* ELzmaStatus is used only as output value for function call */
584 +/* ---------- Interfaces ---------- */
586 +/* There are 3 levels of interfaces:
587 + 1) Dictionary Interface
588 + 2) Buffer Interface
589 + 3) One Call Interface
590 + You can select any of these interfaces, but don't mix functions from different
591 + groups for same object. */
594 +/* There are two variants to allocate state for Dictionary Interface:
595 + 1) LzmaDec_Allocate / LzmaDec_Free
596 + 2) LzmaDec_AllocateProbs / LzmaDec_FreeProbs
597 + You can use variant 2, if you set dictionary buffer manually.
598 + For Buffer Interface you must always use variant 1.
600 +LzmaDec_Allocate* can return:
602 + SZ_ERROR_MEM - Memory allocation error
603 + SZ_ERROR_UNSUPPORTED - Unsupported properties
606 +SRes LzmaDec_AllocateProbs(CLzmaDec *p, const Byte *props, unsigned propsSize, ISzAlloc *alloc);
607 +void LzmaDec_FreeProbs(CLzmaDec *p, ISzAlloc *alloc);
609 +SRes LzmaDec_Allocate(CLzmaDec *state, const Byte *prop, unsigned propsSize, ISzAlloc *alloc);
610 +void LzmaDec_Free(CLzmaDec *state, ISzAlloc *alloc);
612 +/* ---------- Dictionary Interface ---------- */
614 +/* You can use it, if you want to eliminate the overhead for data copying from
615 + dictionary to some other external buffer.
616 + You must work with CLzmaDec variables directly in this interface.
621 + for (each new stream)
624 + while (it needs more decompression)
626 + LzmaDec_DecodeToDic()
627 + use data from CLzmaDec::dic and update CLzmaDec::dicPos
633 +/* LzmaDec_DecodeToDic
635 + The decoding to internal dictionary buffer (CLzmaDec::dic).
636 + You must manually update CLzmaDec::dicPos, if it reaches CLzmaDec::dicBufSize !!!
639 + It has meaning only if the decoding reaches output limit (dicLimit).
640 + LZMA_FINISH_ANY - Decode just dicLimit bytes.
641 + LZMA_FINISH_END - Stream must be finished after dicLimit.
646 + LZMA_STATUS_FINISHED_WITH_MARK
647 + LZMA_STATUS_NOT_FINISHED
648 + LZMA_STATUS_NEEDS_MORE_INPUT
649 + LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK
650 + SZ_ERROR_DATA - Data error
653 +SRes LzmaDec_DecodeToDic(CLzmaDec *p, SizeT dicLimit,
654 + const Byte *src, SizeT *srcLen, ELzmaFinishMode finishMode, ELzmaStatus *status);
657 +/* ---------- Buffer Interface ---------- */
659 +/* It's zlib-like interface.
660 + See LzmaDec_DecodeToDic description for information about STEPS and return results,
661 + but you must use LzmaDec_DecodeToBuf instead of LzmaDec_DecodeToDic and you don't need
662 + to work with CLzmaDec variables manually.
665 + It has meaning only if the decoding reaches output limit (*destLen).
666 + LZMA_FINISH_ANY - Decode just destLen bytes.
667 + LZMA_FINISH_END - Stream must be finished after (*destLen).
670 +SRes LzmaDec_DecodeToBuf(CLzmaDec *p, Byte *dest, SizeT *destLen,
671 + const Byte *src, SizeT *srcLen, ELzmaFinishMode finishMode, ELzmaStatus *status);
674 +/* ---------- One Call Interface ---------- */
679 + It has meaning only if the decoding reaches output limit (*destLen).
680 + LZMA_FINISH_ANY - Decode just destLen bytes.
681 + LZMA_FINISH_END - Stream must be finished after (*destLen).
686 + LZMA_STATUS_FINISHED_WITH_MARK
687 + LZMA_STATUS_NOT_FINISHED
688 + LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK
689 + SZ_ERROR_DATA - Data error
690 + SZ_ERROR_MEM - Memory allocation error
691 + SZ_ERROR_UNSUPPORTED - Unsupported properties
692 + SZ_ERROR_INPUT_EOF - It needs more bytes in input buffer (src).
695 +SRes LzmaDecode(Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen,
696 + const Byte *propData, unsigned propSize, ELzmaFinishMode finishMode,
697 + ELzmaStatus *status, ISzAlloc *alloc);
701 +++ b/include/linux/lzma/LzmaEnc.h
703 +/* LzmaEnc.h -- LZMA Encoder
705 +Copyright (c) 1999-2008 Igor Pavlov
706 +Read LzFind.h for license options */
713 +#define LZMA_PROPS_SIZE 5
715 +typedef struct _CLzmaEncProps
717 + int level; /* 0 <= level <= 9 */
718 + UInt32 dictSize; /* (1 << 12) <= dictSize <= (1 << 27) for 32-bit version
719 + (1 << 12) <= dictSize <= (1 << 30) for 64-bit version
720 + default = (1 << 24) */
721 + int lc; /* 0 <= lc <= 8, default = 3 */
722 + int lp; /* 0 <= lp <= 4, default = 0 */
723 + int pb; /* 0 <= pb <= 4, default = 2 */
724 + int algo; /* 0 - fast, 1 - normal, default = 1 */
725 + int fb; /* 5 <= fb <= 273, default = 32 */
726 + int btMode; /* 0 - hashChain Mode, 1 - binTree mode - normal, default = 1 */
727 + int numHashBytes; /* 2, 3 or 4, default = 4 */
728 + UInt32 mc; /* 1 <= mc <= (1 << 30), default = 32 */
729 + unsigned writeEndMark; /* 0 - do not write EOPM, 1 - write EOPM, default = 0 */
730 + int numThreads; /* 1 or 2, default = 2 */
733 +void LzmaEncProps_Init(CLzmaEncProps *p);
734 +void LzmaEncProps_Normalize(CLzmaEncProps *p);
735 +UInt32 LzmaEncProps_GetDictSize(const CLzmaEncProps *props2);
738 +/* ---------- CLzmaEncHandle Interface ---------- */
740 +/* LzmaEnc_* functions can return the following exit codes:
743 + SZ_ERROR_MEM - Memory allocation error
744 + SZ_ERROR_PARAM - Incorrect paramater in props
745 + SZ_ERROR_WRITE - Write callback error.
746 + SZ_ERROR_PROGRESS - some break from progress callback
747 + SZ_ERROR_THREAD - errors in multithreading functions (only for Mt version)
750 +typedef void * CLzmaEncHandle;
752 +CLzmaEncHandle LzmaEnc_Create(ISzAlloc *alloc);
753 +void LzmaEnc_Destroy(CLzmaEncHandle p, ISzAlloc *alloc, ISzAlloc *allocBig);
754 +SRes LzmaEnc_SetProps(CLzmaEncHandle p, const CLzmaEncProps *props);
755 +SRes LzmaEnc_WriteProperties(CLzmaEncHandle p, Byte *properties, SizeT *size);
756 +SRes LzmaEnc_Encode(CLzmaEncHandle p, ISeqOutStream *outStream, ISeqInStream *inStream,
757 + ICompressProgress *progress, ISzAlloc *alloc, ISzAlloc *allocBig);
758 +SRes LzmaEnc_MemEncode(CLzmaEncHandle p, Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen,
759 + int writeEndMark, ICompressProgress *progress, ISzAlloc *alloc, ISzAlloc *allocBig);
761 +/* ---------- One Call Interface ---------- */
766 + SZ_ERROR_MEM - Memory allocation error
767 + SZ_ERROR_PARAM - Incorrect paramater
768 + SZ_ERROR_OUTPUT_EOF - output buffer overflow
769 + SZ_ERROR_THREAD - errors in multithreading functions (only for Mt version)
772 +SRes LzmaEncode(Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen,
773 + const CLzmaEncProps *props, Byte *propsEncoded, SizeT *propsSize, int writeEndMark,
774 + ICompressProgress *progress, ISzAlloc *alloc, ISzAlloc *allocBig);
778 +++ b/include/linux/lzma/Types.h
780 +/* Types.h -- Basic types
785 +#ifndef __7Z_TYPES_H
786 +#define __7Z_TYPES_H
790 +#define SZ_ERROR_DATA 1
791 +#define SZ_ERROR_MEM 2
792 +#define SZ_ERROR_CRC 3
793 +#define SZ_ERROR_UNSUPPORTED 4
794 +#define SZ_ERROR_PARAM 5
795 +#define SZ_ERROR_INPUT_EOF 6
796 +#define SZ_ERROR_OUTPUT_EOF 7
797 +#define SZ_ERROR_READ 8
798 +#define SZ_ERROR_WRITE 9
799 +#define SZ_ERROR_PROGRESS 10
800 +#define SZ_ERROR_FAIL 11
801 +#define SZ_ERROR_THREAD 12
803 +#define SZ_ERROR_ARCHIVE 16
804 +#define SZ_ERROR_NO_ARCHIVE 17
809 +#define RINOK(x) { int __result__ = (x); if (__result__ != 0) return __result__; }
812 +typedef unsigned char Byte;
813 +typedef short Int16;
814 +typedef unsigned short UInt16;
816 +#ifdef _LZMA_UINT32_IS_ULONG
818 +typedef unsigned long UInt32;
821 +typedef unsigned int UInt32;
824 +/* #define _SZ_NO_INT_64 */
825 +/* define it if your compiler doesn't support 64-bit integers */
827 +#ifdef _SZ_NO_INT_64
830 +typedef unsigned long UInt64;
834 +#if defined(_MSC_VER) || defined(__BORLANDC__)
835 +typedef __int64 Int64;
836 +typedef unsigned __int64 UInt64;
838 +typedef long long int Int64;
839 +typedef unsigned long long int UInt64;
844 +#ifdef _LZMA_NO_SYSTEM_SIZE_T
845 +typedef UInt32 SizeT;
848 +typedef size_t SizeT;
858 +#if _MSC_VER >= 1300
859 +#define MY_NO_INLINE __declspec(noinline)
861 +#define MY_NO_INLINE
864 +#define MY_CDECL __cdecl
865 +#define MY_STD_CALL __stdcall
866 +#define MY_FAST_CALL MY_NO_INLINE __fastcall
872 +#define MY_FAST_CALL
877 +/* The following interfaces use first parameter as pointer to structure */
881 + SRes (*Read)(void *p, void *buf, size_t *size);
882 + /* if (input(*size) != 0 && output(*size) == 0) means end_of_stream.
883 + (output(*size) < input(*size)) is allowed */
888 + size_t (*Write)(void *p, const void *buf, size_t size);
889 + /* Returns: result - the number of actually written bytes.
890 + (result < size) means error */
895 + SRes (*Progress)(void *p, UInt64 inSize, UInt64 outSize);
896 + /* Returns: result. (result != SZ_OK) means break.
897 + Value (UInt64)(Int64)-1 for size means unknown value. */
898 +} ICompressProgress;
902 + void *(*Alloc)(void *p, size_t size);
903 + void (*Free)(void *p, void *address); /* address can be 0 */
906 +#define IAlloc_Alloc(p, size) (p)->Alloc((p), size)
907 +#define IAlloc_Free(p, a) (p)->Free((p), a)
911 +++ b/jffsX-utils/lzma/LzFind.c
913 +/* LzFind.c -- Match finder for LZ algorithms
915 +Copyright (c) 1999-2008 Igor Pavlov
916 +Read LzFind.h for license options */
923 +#define kEmptyHashValue 0
924 +#define kMaxValForNormalize ((UInt32)0xFFFFFFFF)
925 +#define kNormalizeStepMin (1 << 10) /* it must be power of 2 */
926 +#define kNormalizeMask (~(kNormalizeStepMin - 1))
927 +#define kMaxHistorySize ((UInt32)3 << 30)
929 +#define kStartMaxLen 3
931 +static void LzInWindow_Free(CMatchFinder *p, ISzAlloc *alloc)
933 + if (!p->directInput)
935 + alloc->Free(alloc, p->bufferBase);
940 +/* keepSizeBefore + keepSizeAfter + keepSizeReserv must be < 4G) */
942 +static int LzInWindow_Create(CMatchFinder *p, UInt32 keepSizeReserv, ISzAlloc *alloc)
944 + UInt32 blockSize = p->keepSizeBefore + p->keepSizeAfter + keepSizeReserv;
945 + if (p->directInput)
947 + p->blockSize = blockSize;
950 + if (p->bufferBase == 0 || p->blockSize != blockSize)
952 + LzInWindow_Free(p, alloc);
953 + p->blockSize = blockSize;
954 + p->bufferBase = (Byte *)alloc->Alloc(alloc, (size_t)blockSize);
956 + return (p->bufferBase != 0);
959 +Byte *MatchFinder_GetPointerToCurrentPos(CMatchFinder *p) { return p->buffer; }
960 +static Byte MatchFinder_GetIndexByte(CMatchFinder *p, Int32 index) { return p->buffer[index]; }
962 +static UInt32 MatchFinder_GetNumAvailableBytes(CMatchFinder *p) { return p->streamPos - p->pos; }
964 +void MatchFinder_ReduceOffsets(CMatchFinder *p, UInt32 subValue)
966 + p->posLimit -= subValue;
967 + p->pos -= subValue;
968 + p->streamPos -= subValue;
971 +static void MatchFinder_ReadBlock(CMatchFinder *p)
973 + if (p->streamEndWasReached || p->result != SZ_OK)
977 + Byte *dest = p->buffer + (p->streamPos - p->pos);
978 + size_t size = (p->bufferBase + p->blockSize - dest);
981 + p->result = p->stream->Read(p->stream, dest, &size);
982 + if (p->result != SZ_OK)
986 + p->streamEndWasReached = 1;
989 + p->streamPos += (UInt32)size;
990 + if (p->streamPos - p->pos > p->keepSizeAfter)
995 +void MatchFinder_MoveBlock(CMatchFinder *p)
997 + memmove(p->bufferBase,
998 + p->buffer - p->keepSizeBefore,
999 + (size_t)(p->streamPos - p->pos + p->keepSizeBefore));
1000 + p->buffer = p->bufferBase + p->keepSizeBefore;
1003 +int MatchFinder_NeedMove(CMatchFinder *p)
1005 + /* if (p->streamEndWasReached) return 0; */
1006 + return ((size_t)(p->bufferBase + p->blockSize - p->buffer) <= p->keepSizeAfter);
1009 +void MatchFinder_ReadIfRequired(CMatchFinder *p)
1011 + if (p->streamEndWasReached)
1013 + if (p->keepSizeAfter >= p->streamPos - p->pos)
1014 + MatchFinder_ReadBlock(p);
1017 +static void MatchFinder_CheckAndMoveAndRead(CMatchFinder *p)
1019 + if (MatchFinder_NeedMove(p))
1020 + MatchFinder_MoveBlock(p);
1021 + MatchFinder_ReadBlock(p);
1024 +static void MatchFinder_SetDefaultSettings(CMatchFinder *p)
1028 + p->numHashBytes = 4;
1029 + /* p->skipModeBits = 0; */
1030 + p->directInput = 0;
1034 +#define kCrcPoly 0xEDB88320
1036 +void MatchFinder_Construct(CMatchFinder *p)
1039 + p->bufferBase = 0;
1040 + p->directInput = 0;
1042 + MatchFinder_SetDefaultSettings(p);
1044 + for (i = 0; i < 256; i++)
1048 + for (j = 0; j < 8; j++)
1049 + r = (r >> 1) ^ (kCrcPoly & ~((r & 1) - 1));
1054 +static void MatchFinder_FreeThisClassMemory(CMatchFinder *p, ISzAlloc *alloc)
1056 + alloc->Free(alloc, p->hash);
1060 +void MatchFinder_Free(CMatchFinder *p, ISzAlloc *alloc)
1062 + MatchFinder_FreeThisClassMemory(p, alloc);
1063 + LzInWindow_Free(p, alloc);
1066 +static CLzRef* AllocRefs(UInt32 num, ISzAlloc *alloc)
1068 + size_t sizeInBytes = (size_t)num * sizeof(CLzRef);
1069 + if (sizeInBytes / sizeof(CLzRef) != num)
1071 + return (CLzRef *)alloc->Alloc(alloc, sizeInBytes);
1074 +int MatchFinder_Create(CMatchFinder *p, UInt32 historySize,
1075 + UInt32 keepAddBufferBefore, UInt32 matchMaxLen, UInt32 keepAddBufferAfter,
1078 + UInt32 sizeReserv;
1079 + if (historySize > kMaxHistorySize)
1081 + MatchFinder_Free(p, alloc);
1084 + sizeReserv = historySize >> 1;
1085 + if (historySize > ((UInt32)2 << 30))
1086 + sizeReserv = historySize >> 2;
1087 + sizeReserv += (keepAddBufferBefore + matchMaxLen + keepAddBufferAfter) / 2 + (1 << 19);
1089 + p->keepSizeBefore = historySize + keepAddBufferBefore + 1;
1090 + p->keepSizeAfter = matchMaxLen + keepAddBufferAfter;
1091 + /* we need one additional byte, since we use MoveBlock after pos++ and before dictionary using */
1092 + if (LzInWindow_Create(p, sizeReserv, alloc))
1094 + UInt32 newCyclicBufferSize = (historySize /* >> p->skipModeBits */) + 1;
1096 + p->matchMaxLen = matchMaxLen;
1098 + p->fixedHashSize = 0;
1099 + if (p->numHashBytes == 2)
1100 + hs = (1 << 16) - 1;
1103 + hs = historySize - 1;
1109 + /* hs >>= p->skipModeBits; */
1110 + hs |= 0xFFFF; /* don't change it! It's required for Deflate */
1111 + if (hs > (1 << 24))
1113 + if (p->numHashBytes == 3)
1114 + hs = (1 << 24) - 1;
1121 + if (p->numHashBytes > 2) p->fixedHashSize += kHash2Size;
1122 + if (p->numHashBytes > 3) p->fixedHashSize += kHash3Size;
1123 + if (p->numHashBytes > 4) p->fixedHashSize += kHash4Size;
1124 + hs += p->fixedHashSize;
1128 + UInt32 prevSize = p->hashSizeSum + p->numSons;
1130 + p->historySize = historySize;
1131 + p->hashSizeSum = hs;
1132 + p->cyclicBufferSize = newCyclicBufferSize;
1133 + p->numSons = (p->btMode ? newCyclicBufferSize * 2 : newCyclicBufferSize);
1134 + newSize = p->hashSizeSum + p->numSons;
1135 + if (p->hash != 0 && prevSize == newSize)
1137 + MatchFinder_FreeThisClassMemory(p, alloc);
1138 + p->hash = AllocRefs(newSize, alloc);
1141 + p->son = p->hash + p->hashSizeSum;
1146 + MatchFinder_Free(p, alloc);
1150 +static void MatchFinder_SetLimits(CMatchFinder *p)
1152 + UInt32 limit = kMaxValForNormalize - p->pos;
1153 + UInt32 limit2 = p->cyclicBufferSize - p->cyclicBufferPos;
1154 + if (limit2 < limit)
1156 + limit2 = p->streamPos - p->pos;
1157 + if (limit2 <= p->keepSizeAfter)
1163 + limit2 -= p->keepSizeAfter;
1164 + if (limit2 < limit)
1167 + UInt32 lenLimit = p->streamPos - p->pos;
1168 + if (lenLimit > p->matchMaxLen)
1169 + lenLimit = p->matchMaxLen;
1170 + p->lenLimit = lenLimit;
1172 + p->posLimit = p->pos + limit;
1175 +void MatchFinder_Init(CMatchFinder *p)
1178 + for(i = 0; i < p->hashSizeSum; i++)
1179 + p->hash[i] = kEmptyHashValue;
1180 + p->cyclicBufferPos = 0;
1181 + p->buffer = p->bufferBase;
1182 + p->pos = p->streamPos = p->cyclicBufferSize;
1183 + p->result = SZ_OK;
1184 + p->streamEndWasReached = 0;
1185 + MatchFinder_ReadBlock(p);
1186 + MatchFinder_SetLimits(p);
1189 +static UInt32 MatchFinder_GetSubValue(CMatchFinder *p)
1191 + return (p->pos - p->historySize - 1) & kNormalizeMask;
1194 +void MatchFinder_Normalize3(UInt32 subValue, CLzRef *items, UInt32 numItems)
1197 + for (i = 0; i < numItems; i++)
1199 + UInt32 value = items[i];
1200 + if (value <= subValue)
1201 + value = kEmptyHashValue;
1203 + value -= subValue;
1208 +static void MatchFinder_Normalize(CMatchFinder *p)
1210 + UInt32 subValue = MatchFinder_GetSubValue(p);
1211 + MatchFinder_Normalize3(subValue, p->hash, p->hashSizeSum + p->numSons);
1212 + MatchFinder_ReduceOffsets(p, subValue);
1215 +static void MatchFinder_CheckLimits(CMatchFinder *p)
1217 + if (p->pos == kMaxValForNormalize)
1218 + MatchFinder_Normalize(p);
1219 + if (!p->streamEndWasReached && p->keepSizeAfter == p->streamPos - p->pos)
1220 + MatchFinder_CheckAndMoveAndRead(p);
1221 + if (p->cyclicBufferPos == p->cyclicBufferSize)
1222 + p->cyclicBufferPos = 0;
1223 + MatchFinder_SetLimits(p);
1226 +static UInt32 * Hc_GetMatchesSpec(UInt32 lenLimit, UInt32 curMatch, UInt32 pos, const Byte *cur, CLzRef *son,
1227 + UInt32 _cyclicBufferPos, UInt32 _cyclicBufferSize, UInt32 cutValue,
1228 + UInt32 *distances, UInt32 maxLen)
1230 + son[_cyclicBufferPos] = curMatch;
1233 + UInt32 delta = pos - curMatch;
1234 + if (cutValue-- == 0 || delta >= _cyclicBufferSize)
1237 + const Byte *pb = cur - delta;
1238 + curMatch = son[_cyclicBufferPos - delta + ((delta > _cyclicBufferPos) ? _cyclicBufferSize : 0)];
1239 + if (pb[maxLen] == cur[maxLen] && *pb == *cur)
1242 + while(++len != lenLimit)
1243 + if (pb[len] != cur[len])
1247 + *distances++ = maxLen = len;
1248 + *distances++ = delta - 1;
1249 + if (len == lenLimit)
1257 +UInt32 * GetMatchesSpec1(UInt32 lenLimit, UInt32 curMatch, UInt32 pos, const Byte *cur, CLzRef *son,
1258 + UInt32 _cyclicBufferPos, UInt32 _cyclicBufferSize, UInt32 cutValue,
1259 + UInt32 *distances, UInt32 maxLen)
1261 + CLzRef *ptr0 = son + (_cyclicBufferPos << 1) + 1;
1262 + CLzRef *ptr1 = son + (_cyclicBufferPos << 1);
1263 + UInt32 len0 = 0, len1 = 0;
1266 + UInt32 delta = pos - curMatch;
1267 + if (cutValue-- == 0 || delta >= _cyclicBufferSize)
1269 + *ptr0 = *ptr1 = kEmptyHashValue;
1273 + CLzRef *pair = son + ((_cyclicBufferPos - delta + ((delta > _cyclicBufferPos) ? _cyclicBufferSize : 0)) << 1);
1274 + const Byte *pb = cur - delta;
1275 + UInt32 len = (len0 < len1 ? len0 : len1);
1276 + if (pb[len] == cur[len])
1278 + if (++len != lenLimit && pb[len] == cur[len])
1279 + while(++len != lenLimit)
1280 + if (pb[len] != cur[len])
1284 + *distances++ = maxLen = len;
1285 + *distances++ = delta - 1;
1286 + if (len == lenLimit)
1294 + if (pb[len] < cur[len])
1312 +static void SkipMatchesSpec(UInt32 lenLimit, UInt32 curMatch, UInt32 pos, const Byte *cur, CLzRef *son,
1313 + UInt32 _cyclicBufferPos, UInt32 _cyclicBufferSize, UInt32 cutValue)
1315 + CLzRef *ptr0 = son + (_cyclicBufferPos << 1) + 1;
1316 + CLzRef *ptr1 = son + (_cyclicBufferPos << 1);
1317 + UInt32 len0 = 0, len1 = 0;
1320 + UInt32 delta = pos - curMatch;
1321 + if (cutValue-- == 0 || delta >= _cyclicBufferSize)
1323 + *ptr0 = *ptr1 = kEmptyHashValue;
1327 + CLzRef *pair = son + ((_cyclicBufferPos - delta + ((delta > _cyclicBufferPos) ? _cyclicBufferSize : 0)) << 1);
1328 + const Byte *pb = cur - delta;
1329 + UInt32 len = (len0 < len1 ? len0 : len1);
1330 + if (pb[len] == cur[len])
1332 + while(++len != lenLimit)
1333 + if (pb[len] != cur[len])
1336 + if (len == lenLimit)
1344 + if (pb[len] < cur[len])
1363 + ++p->cyclicBufferPos; \
1365 + if (++p->pos == p->posLimit) MatchFinder_CheckLimits(p);
1367 +#define MOVE_POS_RET MOVE_POS return offset;
1369 +static void MatchFinder_MovePos(CMatchFinder *p) { MOVE_POS; }
1371 +#define GET_MATCHES_HEADER2(minLen, ret_op) \
1372 + UInt32 lenLimit; UInt32 hashValue; const Byte *cur; UInt32 curMatch; \
1373 + lenLimit = p->lenLimit; { if (lenLimit < minLen) { MatchFinder_MovePos(p); ret_op; }} \
1376 +#define GET_MATCHES_HEADER(minLen) GET_MATCHES_HEADER2(minLen, return 0)
1377 +#define SKIP_HEADER(minLen) GET_MATCHES_HEADER2(minLen, continue)
1379 +#define MF_PARAMS(p) p->pos, p->buffer, p->son, p->cyclicBufferPos, p->cyclicBufferSize, p->cutValue
1381 +#define GET_MATCHES_FOOTER(offset, maxLen) \
1382 + offset = (UInt32)(GetMatchesSpec1(lenLimit, curMatch, MF_PARAMS(p), \
1383 + distances + offset, maxLen) - distances); MOVE_POS_RET;
1385 +#define SKIP_FOOTER \
1386 + SkipMatchesSpec(lenLimit, curMatch, MF_PARAMS(p)); MOVE_POS;
1388 +static UInt32 Bt2_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances)
1391 + GET_MATCHES_HEADER(2)
1393 + curMatch = p->hash[hashValue];
1394 + p->hash[hashValue] = p->pos;
1396 + GET_MATCHES_FOOTER(offset, 1)
1399 +UInt32 Bt3Zip_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances)
1402 + GET_MATCHES_HEADER(3)
1404 + curMatch = p->hash[hashValue];
1405 + p->hash[hashValue] = p->pos;
1407 + GET_MATCHES_FOOTER(offset, 2)
1410 +static UInt32 Bt3_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances)
1412 + UInt32 hash2Value, delta2, maxLen, offset;
1413 + GET_MATCHES_HEADER(3)
1417 + delta2 = p->pos - p->hash[hash2Value];
1418 + curMatch = p->hash[kFix3HashSize + hashValue];
1420 + p->hash[hash2Value] =
1421 + p->hash[kFix3HashSize + hashValue] = p->pos;
1426 + if (delta2 < p->cyclicBufferSize && *(cur - delta2) == *cur)
1428 + for (; maxLen != lenLimit; maxLen++)
1429 + if (cur[(ptrdiff_t)maxLen - delta2] != cur[maxLen])
1431 + distances[0] = maxLen;
1432 + distances[1] = delta2 - 1;
1434 + if (maxLen == lenLimit)
1436 + SkipMatchesSpec(lenLimit, curMatch, MF_PARAMS(p));
1440 + GET_MATCHES_FOOTER(offset, maxLen)
1443 +static UInt32 Bt4_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances)
1445 + UInt32 hash2Value, hash3Value, delta2, delta3, maxLen, offset;
1446 + GET_MATCHES_HEADER(4)
1450 + delta2 = p->pos - p->hash[ hash2Value];
1451 + delta3 = p->pos - p->hash[kFix3HashSize + hash3Value];
1452 + curMatch = p->hash[kFix4HashSize + hashValue];
1454 + p->hash[ hash2Value] =
1455 + p->hash[kFix3HashSize + hash3Value] =
1456 + p->hash[kFix4HashSize + hashValue] = p->pos;
1460 + if (delta2 < p->cyclicBufferSize && *(cur - delta2) == *cur)
1462 + distances[0] = maxLen = 2;
1463 + distances[1] = delta2 - 1;
1466 + if (delta2 != delta3 && delta3 < p->cyclicBufferSize && *(cur - delta3) == *cur)
1469 + distances[offset + 1] = delta3 - 1;
1475 + for (; maxLen != lenLimit; maxLen++)
1476 + if (cur[(ptrdiff_t)maxLen - delta2] != cur[maxLen])
1478 + distances[offset - 2] = maxLen;
1479 + if (maxLen == lenLimit)
1481 + SkipMatchesSpec(lenLimit, curMatch, MF_PARAMS(p));
1487 + GET_MATCHES_FOOTER(offset, maxLen)
1490 +static UInt32 Hc4_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances)
1492 + UInt32 hash2Value, hash3Value, delta2, delta3, maxLen, offset;
1493 + GET_MATCHES_HEADER(4)
1497 + delta2 = p->pos - p->hash[ hash2Value];
1498 + delta3 = p->pos - p->hash[kFix3HashSize + hash3Value];
1499 + curMatch = p->hash[kFix4HashSize + hashValue];
1501 + p->hash[ hash2Value] =
1502 + p->hash[kFix3HashSize + hash3Value] =
1503 + p->hash[kFix4HashSize + hashValue] = p->pos;
1507 + if (delta2 < p->cyclicBufferSize && *(cur - delta2) == *cur)
1509 + distances[0] = maxLen = 2;
1510 + distances[1] = delta2 - 1;
1513 + if (delta2 != delta3 && delta3 < p->cyclicBufferSize && *(cur - delta3) == *cur)
1516 + distances[offset + 1] = delta3 - 1;
1522 + for (; maxLen != lenLimit; maxLen++)
1523 + if (cur[(ptrdiff_t)maxLen - delta2] != cur[maxLen])
1525 + distances[offset - 2] = maxLen;
1526 + if (maxLen == lenLimit)
1528 + p->son[p->cyclicBufferPos] = curMatch;
1534 + offset = (UInt32)(Hc_GetMatchesSpec(lenLimit, curMatch, MF_PARAMS(p),
1535 + distances + offset, maxLen) - (distances));
1539 +UInt32 Hc3Zip_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances)
1542 + GET_MATCHES_HEADER(3)
1544 + curMatch = p->hash[hashValue];
1545 + p->hash[hashValue] = p->pos;
1546 + offset = (UInt32)(Hc_GetMatchesSpec(lenLimit, curMatch, MF_PARAMS(p),
1547 + distances, 2) - (distances));
1551 +static void Bt2_MatchFinder_Skip(CMatchFinder *p, UInt32 num)
1557 + curMatch = p->hash[hashValue];
1558 + p->hash[hashValue] = p->pos;
1561 + while (--num != 0);
1564 +void Bt3Zip_MatchFinder_Skip(CMatchFinder *p, UInt32 num)
1570 + curMatch = p->hash[hashValue];
1571 + p->hash[hashValue] = p->pos;
1574 + while (--num != 0);
1577 +static void Bt3_MatchFinder_Skip(CMatchFinder *p, UInt32 num)
1581 + UInt32 hash2Value;
1584 + curMatch = p->hash[kFix3HashSize + hashValue];
1585 + p->hash[hash2Value] =
1586 + p->hash[kFix3HashSize + hashValue] = p->pos;
1589 + while (--num != 0);
1592 +static void Bt4_MatchFinder_Skip(CMatchFinder *p, UInt32 num)
1596 + UInt32 hash2Value, hash3Value;
1599 + curMatch = p->hash[kFix4HashSize + hashValue];
1600 + p->hash[ hash2Value] =
1601 + p->hash[kFix3HashSize + hash3Value] = p->pos;
1602 + p->hash[kFix4HashSize + hashValue] = p->pos;
1605 + while (--num != 0);
1608 +static void Hc4_MatchFinder_Skip(CMatchFinder *p, UInt32 num)
1612 + UInt32 hash2Value, hash3Value;
1615 + curMatch = p->hash[kFix4HashSize + hashValue];
1616 + p->hash[ hash2Value] =
1617 + p->hash[kFix3HashSize + hash3Value] =
1618 + p->hash[kFix4HashSize + hashValue] = p->pos;
1619 + p->son[p->cyclicBufferPos] = curMatch;
1622 + while (--num != 0);
1625 +void Hc3Zip_MatchFinder_Skip(CMatchFinder *p, UInt32 num)
1631 + curMatch = p->hash[hashValue];
1632 + p->hash[hashValue] = p->pos;
1633 + p->son[p->cyclicBufferPos] = curMatch;
1636 + while (--num != 0);
1639 +void MatchFinder_CreateVTable(CMatchFinder *p, IMatchFinder *vTable)
1641 + vTable->Init = (Mf_Init_Func)MatchFinder_Init;
1642 + vTable->GetIndexByte = (Mf_GetIndexByte_Func)MatchFinder_GetIndexByte;
1643 + vTable->GetNumAvailableBytes = (Mf_GetNumAvailableBytes_Func)MatchFinder_GetNumAvailableBytes;
1644 + vTable->GetPointerToCurrentPos = (Mf_GetPointerToCurrentPos_Func)MatchFinder_GetPointerToCurrentPos;
1647 + vTable->GetMatches = (Mf_GetMatches_Func)Hc4_MatchFinder_GetMatches;
1648 + vTable->Skip = (Mf_Skip_Func)Hc4_MatchFinder_Skip;
1650 + else if (p->numHashBytes == 2)
1652 + vTable->GetMatches = (Mf_GetMatches_Func)Bt2_MatchFinder_GetMatches;
1653 + vTable->Skip = (Mf_Skip_Func)Bt2_MatchFinder_Skip;
1655 + else if (p->numHashBytes == 3)
1657 + vTable->GetMatches = (Mf_GetMatches_Func)Bt3_MatchFinder_GetMatches;
1658 + vTable->Skip = (Mf_Skip_Func)Bt3_MatchFinder_Skip;
1662 + vTable->GetMatches = (Mf_GetMatches_Func)Bt4_MatchFinder_GetMatches;
1663 + vTable->Skip = (Mf_Skip_Func)Bt4_MatchFinder_Skip;
1667 +++ b/jffsX-utils/lzma/LzmaDec.c
1669 +/* LzmaDec.c -- LZMA Decoder
1671 +Copyright (c) 1999-2008 Igor Pavlov
1672 +Read LzmaDec.h for license options */
1674 +#include "LzmaDec.h"
1676 +#include <string.h>
1678 +#define kNumTopBits 24
1679 +#define kTopValue ((UInt32)1 << kNumTopBits)
1681 +#define kNumBitModelTotalBits 11
1682 +#define kBitModelTotal (1 << kNumBitModelTotalBits)
1683 +#define kNumMoveBits 5
1685 +#define RC_INIT_SIZE 5
1687 +#define NORMALIZE if (range < kTopValue) { range <<= 8; code = (code << 8) | (*buf++); }
1689 +#define IF_BIT_0(p) ttt = *(p); NORMALIZE; bound = (range >> kNumBitModelTotalBits) * ttt; if (code < bound)
1690 +#define UPDATE_0(p) range = bound; *(p) = (CLzmaProb)(ttt + ((kBitModelTotal - ttt) >> kNumMoveBits));
1691 +#define UPDATE_1(p) range -= bound; code -= bound; *(p) = (CLzmaProb)(ttt - (ttt >> kNumMoveBits));
1692 +#define GET_BIT2(p, i, A0, A1) IF_BIT_0(p) \
1693 + { UPDATE_0(p); i = (i + i); A0; } else \
1694 + { UPDATE_1(p); i = (i + i) + 1; A1; }
1695 +#define GET_BIT(p, i) GET_BIT2(p, i, ; , ;)
1697 +#define TREE_GET_BIT(probs, i) { GET_BIT((probs + i), i); }
1698 +#define TREE_DECODE(probs, limit, i) \
1699 + { i = 1; do { TREE_GET_BIT(probs, i); } while (i < limit); i -= limit; }
1701 +/* #define _LZMA_SIZE_OPT */
1703 +#ifdef _LZMA_SIZE_OPT
1704 +#define TREE_6_DECODE(probs, i) TREE_DECODE(probs, (1 << 6), i)
1706 +#define TREE_6_DECODE(probs, i) \
1708 + TREE_GET_BIT(probs, i); \
1709 + TREE_GET_BIT(probs, i); \
1710 + TREE_GET_BIT(probs, i); \
1711 + TREE_GET_BIT(probs, i); \
1712 + TREE_GET_BIT(probs, i); \
1713 + TREE_GET_BIT(probs, i); \
1717 +#define NORMALIZE_CHECK if (range < kTopValue) { if (buf >= bufLimit) return DUMMY_ERROR; range <<= 8; code = (code << 8) | (*buf++); }
1719 +#define IF_BIT_0_CHECK(p) ttt = *(p); NORMALIZE_CHECK; bound = (range >> kNumBitModelTotalBits) * ttt; if (code < bound)
1720 +#define UPDATE_0_CHECK range = bound;
1721 +#define UPDATE_1_CHECK range -= bound; code -= bound;
1722 +#define GET_BIT2_CHECK(p, i, A0, A1) IF_BIT_0_CHECK(p) \
1723 + { UPDATE_0_CHECK; i = (i + i); A0; } else \
1724 + { UPDATE_1_CHECK; i = (i + i) + 1; A1; }
1725 +#define GET_BIT_CHECK(p, i) GET_BIT2_CHECK(p, i, ; , ;)
1726 +#define TREE_DECODE_CHECK(probs, limit, i) \
1727 + { i = 1; do { GET_BIT_CHECK(probs + i, i) } while(i < limit); i -= limit; }
1730 +#define kNumPosBitsMax 4
1731 +#define kNumPosStatesMax (1 << kNumPosBitsMax)
1733 +#define kLenNumLowBits 3
1734 +#define kLenNumLowSymbols (1 << kLenNumLowBits)
1735 +#define kLenNumMidBits 3
1736 +#define kLenNumMidSymbols (1 << kLenNumMidBits)
1737 +#define kLenNumHighBits 8
1738 +#define kLenNumHighSymbols (1 << kLenNumHighBits)
1740 +#define LenChoice 0
1741 +#define LenChoice2 (LenChoice + 1)
1742 +#define LenLow (LenChoice2 + 1)
1743 +#define LenMid (LenLow + (kNumPosStatesMax << kLenNumLowBits))
1744 +#define LenHigh (LenMid + (kNumPosStatesMax << kLenNumMidBits))
1745 +#define kNumLenProbs (LenHigh + kLenNumHighSymbols)
1748 +#define kNumStates 12
1749 +#define kNumLitStates 7
1751 +#define kStartPosModelIndex 4
1752 +#define kEndPosModelIndex 14
1753 +#define kNumFullDistances (1 << (kEndPosModelIndex >> 1))
1755 +#define kNumPosSlotBits 6
1756 +#define kNumLenToPosStates 4
1758 +#define kNumAlignBits 4
1759 +#define kAlignTableSize (1 << kNumAlignBits)
1761 +#define kMatchMinLen 2
1762 +#define kMatchSpecLenStart (kMatchMinLen + kLenNumLowSymbols + kLenNumMidSymbols + kLenNumHighSymbols)
1765 +#define IsRep (IsMatch + (kNumStates << kNumPosBitsMax))
1766 +#define IsRepG0 (IsRep + kNumStates)
1767 +#define IsRepG1 (IsRepG0 + kNumStates)
1768 +#define IsRepG2 (IsRepG1 + kNumStates)
1769 +#define IsRep0Long (IsRepG2 + kNumStates)
1770 +#define PosSlot (IsRep0Long + (kNumStates << kNumPosBitsMax))
1771 +#define SpecPos (PosSlot + (kNumLenToPosStates << kNumPosSlotBits))
1772 +#define Align (SpecPos + kNumFullDistances - kEndPosModelIndex)
1773 +#define LenCoder (Align + kAlignTableSize)
1774 +#define RepLenCoder (LenCoder + kNumLenProbs)
1775 +#define Literal (RepLenCoder + kNumLenProbs)
1777 +#define LZMA_BASE_SIZE 1846
1778 +#define LZMA_LIT_SIZE 768
1780 +#define LzmaProps_GetNumProbs(p) ((UInt32)LZMA_BASE_SIZE + (LZMA_LIT_SIZE << ((p)->lc + (p)->lp)))
1782 +#if Literal != LZMA_BASE_SIZE
1783 +StopCompilingDueBUG
1787 +#define LZMA_STREAM_WAS_FINISHED_ID (-1)
1788 +#define LZMA_SPEC_LEN_OFFSET (-3)
1791 +Byte kLiteralNextStates[kNumStates * 2] =
1793 + 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 4, 5,
1794 + 7, 7, 7, 7, 7, 7, 7, 10, 10, 10, 10, 10
1797 +#define LZMA_DIC_MIN (1 << 12)
1799 +/* First LZMA-symbol is always decoded.
1800 +And it decodes new LZMA-symbols while (buf < bufLimit), but "buf" is without last normalization
1806 + < kMatchSpecLenStart : normal remain
1807 + = kMatchSpecLenStart : finished
1808 + = kMatchSpecLenStart + 1 : Flush marker
1809 + = kMatchSpecLenStart + 2 : State Init Marker
1812 +static int MY_FAST_CALL LzmaDec_DecodeReal(CLzmaDec *p, SizeT limit, const Byte *bufLimit)
1814 + CLzmaProb *probs = p->probs;
1816 + unsigned state = p->state;
1817 + UInt32 rep0 = p->reps[0], rep1 = p->reps[1], rep2 = p->reps[2], rep3 = p->reps[3];
1818 + unsigned pbMask = ((unsigned)1 << (p->prop.pb)) - 1;
1819 + unsigned lpMask = ((unsigned)1 << (p->prop.lp)) - 1;
1820 + unsigned lc = p->prop.lc;
1822 + Byte *dic = p->dic;
1823 + SizeT dicBufSize = p->dicBufSize;
1824 + SizeT dicPos = p->dicPos;
1826 + UInt32 processedPos = p->processedPos;
1827 + UInt32 checkDicSize = p->checkDicSize;
1830 + const Byte *buf = p->buf;
1831 + UInt32 range = p->range;
1832 + UInt32 code = p->code;
1839 + unsigned posState = processedPos & pbMask;
1841 + prob = probs + IsMatch + (state << kNumPosBitsMax) + posState;
1846 + prob = probs + Literal;
1847 + if (checkDicSize != 0 || processedPos != 0)
1848 + prob += (LZMA_LIT_SIZE * (((processedPos & lpMask) << lc) +
1849 + (dic[(dicPos == 0 ? dicBufSize : dicPos) - 1] >> (8 - lc))));
1851 + if (state < kNumLitStates)
1854 + do { GET_BIT(prob + symbol, symbol) } while (symbol < 0x100);
1858 + unsigned matchByte = p->dic[(dicPos - rep0) + ((dicPos < rep0) ? dicBufSize : 0)];
1859 + unsigned offs = 0x100;
1864 + CLzmaProb *probLit;
1866 + bit = (matchByte & offs);
1867 + probLit = prob + offs + bit + symbol;
1868 + GET_BIT2(probLit, symbol, offs &= ~bit, offs &= bit)
1870 + while (symbol < 0x100);
1872 + dic[dicPos++] = (Byte)symbol;
1875 + state = kLiteralNextStates[state];
1876 + /* if (state < 4) state = 0; else if (state < 10) state -= 3; else state -= 6; */
1882 + prob = probs + IsRep + state;
1886 + state += kNumStates;
1887 + prob = probs + LenCoder;
1892 + if (checkDicSize == 0 && processedPos == 0)
1893 + return SZ_ERROR_DATA;
1894 + prob = probs + IsRepG0 + state;
1898 + prob = probs + IsRep0Long + (state << kNumPosBitsMax) + posState;
1902 + dic[dicPos] = dic[(dicPos - rep0) + ((dicPos < rep0) ? dicBufSize : 0)];
1905 + state = state < kNumLitStates ? 9 : 11;
1914 + prob = probs + IsRepG1 + state;
1923 + prob = probs + IsRepG2 + state;
1940 + state = state < kNumLitStates ? 8 : 11;
1941 + prob = probs + RepLenCoder;
1944 + unsigned limit, offset;
1945 + CLzmaProb *probLen = prob + LenChoice;
1948 + UPDATE_0(probLen);
1949 + probLen = prob + LenLow + (posState << kLenNumLowBits);
1951 + limit = (1 << kLenNumLowBits);
1955 + UPDATE_1(probLen);
1956 + probLen = prob + LenChoice2;
1959 + UPDATE_0(probLen);
1960 + probLen = prob + LenMid + (posState << kLenNumMidBits);
1961 + offset = kLenNumLowSymbols;
1962 + limit = (1 << kLenNumMidBits);
1966 + UPDATE_1(probLen);
1967 + probLen = prob + LenHigh;
1968 + offset = kLenNumLowSymbols + kLenNumMidSymbols;
1969 + limit = (1 << kLenNumHighBits);
1972 + TREE_DECODE(probLen, limit, len);
1976 + if (state >= kNumStates)
1979 + prob = probs + PosSlot +
1980 + ((len < kNumLenToPosStates ? len : kNumLenToPosStates - 1) << kNumPosSlotBits);
1981 + TREE_6_DECODE(prob, distance);
1982 + if (distance >= kStartPosModelIndex)
1984 + unsigned posSlot = (unsigned)distance;
1985 + int numDirectBits = (int)(((distance >> 1) - 1));
1986 + distance = (2 | (distance & 1));
1987 + if (posSlot < kEndPosModelIndex)
1989 + distance <<= numDirectBits;
1990 + prob = probs + SpecPos + distance - posSlot - 1;
1996 + GET_BIT2(prob + i, i, ; , distance |= mask);
1999 + while(--numDirectBits != 0);
2004 + numDirectBits -= kNumAlignBits;
2013 + t = (0 - ((UInt32)code >> 31)); /* (UInt32)((Int32)code >> 31) */
2014 + distance = (distance << 1) + (t + 1);
2015 + code += range & t;
2019 + if (code >= range)
2026 + while (--numDirectBits != 0);
2027 + prob = probs + Align;
2028 + distance <<= kNumAlignBits;
2031 + GET_BIT2(prob + i, i, ; , distance |= 1);
2032 + GET_BIT2(prob + i, i, ; , distance |= 2);
2033 + GET_BIT2(prob + i, i, ; , distance |= 4);
2034 + GET_BIT2(prob + i, i, ; , distance |= 8);
2036 + if (distance == (UInt32)0xFFFFFFFF)
2038 + len += kMatchSpecLenStart;
2039 + state -= kNumStates;
2047 + rep0 = distance + 1;
2048 + if (checkDicSize == 0)
2050 + if (distance >= processedPos)
2051 + return SZ_ERROR_DATA;
2053 + else if (distance >= checkDicSize)
2054 + return SZ_ERROR_DATA;
2055 + state = (state < kNumStates + kNumLitStates) ? kNumLitStates : kNumLitStates + 3;
2056 + /* state = kLiteralNextStates[state]; */
2059 + len += kMatchMinLen;
2062 + SizeT rem = limit - dicPos;
2063 + unsigned curLen = ((rem < len) ? (unsigned)rem : len);
2064 + SizeT pos = (dicPos - rep0) + ((dicPos < rep0) ? dicBufSize : 0);
2066 + processedPos += curLen;
2069 + if (pos + curLen <= dicBufSize)
2071 + Byte *dest = dic + dicPos;
2072 + ptrdiff_t src = (ptrdiff_t)pos - (ptrdiff_t)dicPos;
2073 + const Byte *lim = dest + curLen;
2076 + *(dest) = (Byte)*(dest + src);
2077 + while (++dest != lim);
2083 + dic[dicPos++] = dic[pos];
2084 + if (++pos == dicBufSize)
2087 + while (--curLen != 0);
2092 + while (dicPos < limit && buf < bufLimit);
2097 + p->remainLen = len;
2098 + p->dicPos = dicPos;
2099 + p->processedPos = processedPos;
2100 + p->reps[0] = rep0;
2101 + p->reps[1] = rep1;
2102 + p->reps[2] = rep2;
2103 + p->reps[3] = rep3;
2109 +static void MY_FAST_CALL LzmaDec_WriteRem(CLzmaDec *p, SizeT limit)
2111 + if (p->remainLen != 0 && p->remainLen < kMatchSpecLenStart)
2113 + Byte *dic = p->dic;
2114 + SizeT dicPos = p->dicPos;
2115 + SizeT dicBufSize = p->dicBufSize;
2116 + unsigned len = p->remainLen;
2117 + UInt32 rep0 = p->reps[0];
2118 + if (limit - dicPos < len)
2119 + len = (unsigned)(limit - dicPos);
2121 + if (p->checkDicSize == 0 && p->prop.dicSize - p->processedPos <= len)
2122 + p->checkDicSize = p->prop.dicSize;
2124 + p->processedPos += len;
2125 + p->remainLen -= len;
2126 + while (len-- != 0)
2128 + dic[dicPos] = dic[(dicPos - rep0) + ((dicPos < rep0) ? dicBufSize : 0)];
2131 + p->dicPos = dicPos;
2135 +/* LzmaDec_DecodeReal2 decodes LZMA-symbols and sets p->needFlush and p->needInit, if required. */
2137 +static int MY_FAST_CALL LzmaDec_DecodeReal2(CLzmaDec *p, SizeT limit, const Byte *bufLimit)
2141 + SizeT limit2 = limit;
2142 + if (p->checkDicSize == 0)
2144 + UInt32 rem = p->prop.dicSize - p->processedPos;
2145 + if (limit - p->dicPos > rem)
2146 + limit2 = p->dicPos + rem;
2148 + RINOK(LzmaDec_DecodeReal(p, limit2, bufLimit));
2149 + if (p->processedPos >= p->prop.dicSize)
2150 + p->checkDicSize = p->prop.dicSize;
2151 + LzmaDec_WriteRem(p, limit);
2153 + while (p->dicPos < limit && p->buf < bufLimit && p->remainLen < kMatchSpecLenStart);
2155 + if (p->remainLen > kMatchSpecLenStart)
2157 + p->remainLen = kMatchSpecLenStart;
2164 + DUMMY_ERROR, /* unexpected end of input stream */
2170 +static ELzmaDummy LzmaDec_TryDummy(const CLzmaDec *p, const Byte *buf, SizeT inSize)
2172 + UInt32 range = p->range;
2173 + UInt32 code = p->code;
2174 + const Byte *bufLimit = buf + inSize;
2175 + CLzmaProb *probs = p->probs;
2176 + unsigned state = p->state;
2183 + unsigned posState = (p->processedPos) & ((1 << p->prop.pb) - 1);
2185 + prob = probs + IsMatch + (state << kNumPosBitsMax) + posState;
2186 + IF_BIT_0_CHECK(prob)
2190 + /* if (bufLimit - buf >= 7) return DUMMY_LIT; */
2192 + prob = probs + Literal;
2193 + if (p->checkDicSize != 0 || p->processedPos != 0)
2194 + prob += (LZMA_LIT_SIZE *
2195 + ((((p->processedPos) & ((1 << (p->prop.lp)) - 1)) << p->prop.lc) +
2196 + (p->dic[(p->dicPos == 0 ? p->dicBufSize : p->dicPos) - 1] >> (8 - p->prop.lc))));
2198 + if (state < kNumLitStates)
2200 + unsigned symbol = 1;
2201 + do { GET_BIT_CHECK(prob + symbol, symbol) } while (symbol < 0x100);
2205 + unsigned matchByte = p->dic[p->dicPos - p->reps[0] +
2206 + ((p->dicPos < p->reps[0]) ? p->dicBufSize : 0)];
2207 + unsigned offs = 0x100;
2208 + unsigned symbol = 1;
2212 + CLzmaProb *probLit;
2214 + bit = (matchByte & offs);
2215 + probLit = prob + offs + bit + symbol;
2216 + GET_BIT2_CHECK(probLit, symbol, offs &= ~bit, offs &= bit)
2218 + while (symbol < 0x100);
2227 + prob = probs + IsRep + state;
2228 + IF_BIT_0_CHECK(prob)
2232 + prob = probs + LenCoder;
2233 + res = DUMMY_MATCH;
2239 + prob = probs + IsRepG0 + state;
2240 + IF_BIT_0_CHECK(prob)
2243 + prob = probs + IsRep0Long + (state << kNumPosBitsMax) + posState;
2244 + IF_BIT_0_CHECK(prob)
2258 + prob = probs + IsRepG1 + state;
2259 + IF_BIT_0_CHECK(prob)
2266 + prob = probs + IsRepG2 + state;
2267 + IF_BIT_0_CHECK(prob)
2277 + state = kNumStates;
2278 + prob = probs + RepLenCoder;
2281 + unsigned limit, offset;
2282 + CLzmaProb *probLen = prob + LenChoice;
2283 + IF_BIT_0_CHECK(probLen)
2286 + probLen = prob + LenLow + (posState << kLenNumLowBits);
2288 + limit = 1 << kLenNumLowBits;
2293 + probLen = prob + LenChoice2;
2294 + IF_BIT_0_CHECK(probLen)
2297 + probLen = prob + LenMid + (posState << kLenNumMidBits);
2298 + offset = kLenNumLowSymbols;
2299 + limit = 1 << kLenNumMidBits;
2304 + probLen = prob + LenHigh;
2305 + offset = kLenNumLowSymbols + kLenNumMidSymbols;
2306 + limit = 1 << kLenNumHighBits;
2309 + TREE_DECODE_CHECK(probLen, limit, len);
2316 + prob = probs + PosSlot +
2317 + ((len < kNumLenToPosStates ? len : kNumLenToPosStates - 1) <<
2319 + TREE_DECODE_CHECK(prob, 1 << kNumPosSlotBits, posSlot);
2320 + if (posSlot >= kStartPosModelIndex)
2322 + int numDirectBits = ((posSlot >> 1) - 1);
2324 + /* if (bufLimit - buf >= 8) return DUMMY_MATCH; */
2326 + if (posSlot < kEndPosModelIndex)
2328 + prob = probs + SpecPos + ((2 | (posSlot & 1)) << numDirectBits) - posSlot - 1;
2332 + numDirectBits -= kNumAlignBits;
2337 + code -= range & (((code - range) >> 31) - 1);
2338 + /* if (code >= range) code -= range; */
2340 + while (--numDirectBits != 0);
2341 + prob = probs + Align;
2342 + numDirectBits = kNumAlignBits;
2348 + GET_BIT_CHECK(prob + i, i);
2350 + while(--numDirectBits != 0);
2361 +static void LzmaDec_InitRc(CLzmaDec *p, const Byte *data)
2363 + p->code = ((UInt32)data[1] << 24) | ((UInt32)data[2] << 16) | ((UInt32)data[3] << 8) | ((UInt32)data[4]);
2364 + p->range = 0xFFFFFFFF;
2368 +static void LzmaDec_InitDicAndState(CLzmaDec *p, Bool initDic, Bool initState)
2372 + p->tempBufSize = 0;
2376 + p->processedPos = 0;
2377 + p->checkDicSize = 0;
2378 + p->needInitState = 1;
2381 + p->needInitState = 1;
2384 +void LzmaDec_Init(CLzmaDec *p)
2387 + LzmaDec_InitDicAndState(p, True, True);
2390 +static void LzmaDec_InitStateReal(CLzmaDec *p)
2392 + UInt32 numProbs = Literal + ((UInt32)LZMA_LIT_SIZE << (p->prop.lc + p->prop.lp));
2394 + CLzmaProb *probs = p->probs;
2395 + for (i = 0; i < numProbs; i++)
2396 + probs[i] = kBitModelTotal >> 1;
2397 + p->reps[0] = p->reps[1] = p->reps[2] = p->reps[3] = 1;
2399 + p->needInitState = 0;
2402 +SRes LzmaDec_DecodeToDic(CLzmaDec *p, SizeT dicLimit, const Byte *src, SizeT *srcLen,
2403 + ELzmaFinishMode finishMode, ELzmaStatus *status)
2405 + SizeT inSize = *srcLen;
2407 + LzmaDec_WriteRem(p, dicLimit);
2409 + *status = LZMA_STATUS_NOT_SPECIFIED;
2411 + while (p->remainLen != kMatchSpecLenStart)
2413 + int checkEndMarkNow;
2415 + if (p->needFlush != 0)
2417 + for (; inSize > 0 && p->tempBufSize < RC_INIT_SIZE; (*srcLen)++, inSize--)
2418 + p->tempBuf[p->tempBufSize++] = *src++;
2419 + if (p->tempBufSize < RC_INIT_SIZE)
2421 + *status = LZMA_STATUS_NEEDS_MORE_INPUT;
2424 + if (p->tempBuf[0] != 0)
2425 + return SZ_ERROR_DATA;
2427 + LzmaDec_InitRc(p, p->tempBuf);
2428 + p->tempBufSize = 0;
2431 + checkEndMarkNow = 0;
2432 + if (p->dicPos >= dicLimit)
2434 + if (p->remainLen == 0 && p->code == 0)
2436 + *status = LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK;
2439 + if (finishMode == LZMA_FINISH_ANY)
2441 + *status = LZMA_STATUS_NOT_FINISHED;
2444 + if (p->remainLen != 0)
2446 + *status = LZMA_STATUS_NOT_FINISHED;
2447 + return SZ_ERROR_DATA;
2449 + checkEndMarkNow = 1;
2452 + if (p->needInitState)
2453 + LzmaDec_InitStateReal(p);
2455 + if (p->tempBufSize == 0)
2458 + const Byte *bufLimit;
2459 + if (inSize < LZMA_REQUIRED_INPUT_MAX || checkEndMarkNow)
2461 + int dummyRes = LzmaDec_TryDummy(p, src, inSize);
2462 + if (dummyRes == DUMMY_ERROR)
2464 + memcpy(p->tempBuf, src, inSize);
2465 + p->tempBufSize = (unsigned)inSize;
2466 + (*srcLen) += inSize;
2467 + *status = LZMA_STATUS_NEEDS_MORE_INPUT;
2470 + if (checkEndMarkNow && dummyRes != DUMMY_MATCH)
2472 + *status = LZMA_STATUS_NOT_FINISHED;
2473 + return SZ_ERROR_DATA;
2478 + bufLimit = src + inSize - LZMA_REQUIRED_INPUT_MAX;
2480 + if (LzmaDec_DecodeReal2(p, dicLimit, bufLimit) != 0)
2481 + return SZ_ERROR_DATA;
2482 + processed = p->buf - src;
2483 + (*srcLen) += processed;
2485 + inSize -= processed;
2489 + unsigned rem = p->tempBufSize, lookAhead = 0;
2490 + while (rem < LZMA_REQUIRED_INPUT_MAX && lookAhead < inSize)
2491 + p->tempBuf[rem++] = src[lookAhead++];
2492 + p->tempBufSize = rem;
2493 + if (rem < LZMA_REQUIRED_INPUT_MAX || checkEndMarkNow)
2495 + int dummyRes = LzmaDec_TryDummy(p, p->tempBuf, rem);
2496 + if (dummyRes == DUMMY_ERROR)
2498 + (*srcLen) += lookAhead;
2499 + *status = LZMA_STATUS_NEEDS_MORE_INPUT;
2502 + if (checkEndMarkNow && dummyRes != DUMMY_MATCH)
2504 + *status = LZMA_STATUS_NOT_FINISHED;
2505 + return SZ_ERROR_DATA;
2508 + p->buf = p->tempBuf;
2509 + if (LzmaDec_DecodeReal2(p, dicLimit, p->buf) != 0)
2510 + return SZ_ERROR_DATA;
2511 + lookAhead -= (rem - (unsigned)(p->buf - p->tempBuf));
2512 + (*srcLen) += lookAhead;
2514 + inSize -= lookAhead;
2515 + p->tempBufSize = 0;
2519 + *status = LZMA_STATUS_FINISHED_WITH_MARK;
2520 + return (p->code == 0) ? SZ_OK : SZ_ERROR_DATA;
2523 +SRes LzmaDec_DecodeToBuf(CLzmaDec *p, Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen, ELzmaFinishMode finishMode, ELzmaStatus *status)
2525 + SizeT outSize = *destLen;
2526 + SizeT inSize = *srcLen;
2527 + *srcLen = *destLen = 0;
2530 + SizeT inSizeCur = inSize, outSizeCur, dicPos;
2531 + ELzmaFinishMode curFinishMode;
2533 + if (p->dicPos == p->dicBufSize)
2535 + dicPos = p->dicPos;
2536 + if (outSize > p->dicBufSize - dicPos)
2538 + outSizeCur = p->dicBufSize;
2539 + curFinishMode = LZMA_FINISH_ANY;
2543 + outSizeCur = dicPos + outSize;
2544 + curFinishMode = finishMode;
2547 + res = LzmaDec_DecodeToDic(p, outSizeCur, src, &inSizeCur, curFinishMode, status);
2549 + inSize -= inSizeCur;
2550 + *srcLen += inSizeCur;
2551 + outSizeCur = p->dicPos - dicPos;
2552 + memcpy(dest, p->dic + dicPos, outSizeCur);
2553 + dest += outSizeCur;
2554 + outSize -= outSizeCur;
2555 + *destLen += outSizeCur;
2558 + if (outSizeCur == 0 || outSize == 0)
2563 +void LzmaDec_FreeProbs(CLzmaDec *p, ISzAlloc *alloc)
2565 + alloc->Free(alloc, p->probs);
2569 +static void LzmaDec_FreeDict(CLzmaDec *p, ISzAlloc *alloc)
2571 + alloc->Free(alloc, p->dic);
2575 +void LzmaDec_Free(CLzmaDec *p, ISzAlloc *alloc)
2577 + LzmaDec_FreeProbs(p, alloc);
2578 + LzmaDec_FreeDict(p, alloc);
2581 +SRes LzmaProps_Decode(CLzmaProps *p, const Byte *data, unsigned size)
2586 + if (size < LZMA_PROPS_SIZE)
2587 + return SZ_ERROR_UNSUPPORTED;
2589 + dicSize = data[1] | ((UInt32)data[2] << 8) | ((UInt32)data[3] << 16) | ((UInt32)data[4] << 24);
2591 + if (dicSize < LZMA_DIC_MIN)
2592 + dicSize = LZMA_DIC_MIN;
2593 + p->dicSize = dicSize;
2596 + if (d >= (9 * 5 * 5))
2597 + return SZ_ERROR_UNSUPPORTED;
2607 +static SRes LzmaDec_AllocateProbs2(CLzmaDec *p, const CLzmaProps *propNew, ISzAlloc *alloc)
2609 + UInt32 numProbs = LzmaProps_GetNumProbs(propNew);
2610 + if (p->probs == 0 || numProbs != p->numProbs)
2612 + LzmaDec_FreeProbs(p, alloc);
2613 + p->probs = (CLzmaProb *)alloc->Alloc(alloc, numProbs * sizeof(CLzmaProb));
2614 + p->numProbs = numProbs;
2615 + if (p->probs == 0)
2616 + return SZ_ERROR_MEM;
2621 +SRes LzmaDec_AllocateProbs(CLzmaDec *p, const Byte *props, unsigned propsSize, ISzAlloc *alloc)
2623 + CLzmaProps propNew;
2624 + RINOK(LzmaProps_Decode(&propNew, props, propsSize));
2625 + RINOK(LzmaDec_AllocateProbs2(p, &propNew, alloc));
2626 + p->prop = propNew;
2630 +SRes LzmaDec_Allocate(CLzmaDec *p, const Byte *props, unsigned propsSize, ISzAlloc *alloc)
2632 + CLzmaProps propNew;
2634 + RINOK(LzmaProps_Decode(&propNew, props, propsSize));
2635 + RINOK(LzmaDec_AllocateProbs2(p, &propNew, alloc));
2636 + dicBufSize = propNew.dicSize;
2637 + if (p->dic == 0 || dicBufSize != p->dicBufSize)
2639 + LzmaDec_FreeDict(p, alloc);
2640 + p->dic = (Byte *)alloc->Alloc(alloc, dicBufSize);
2643 + LzmaDec_FreeProbs(p, alloc);
2644 + return SZ_ERROR_MEM;
2647 + p->dicBufSize = dicBufSize;
2648 + p->prop = propNew;
2652 +SRes LzmaDecode(Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen,
2653 + const Byte *propData, unsigned propSize, ELzmaFinishMode finishMode,
2654 + ELzmaStatus *status, ISzAlloc *alloc)
2658 + SizeT inSize = *srcLen;
2659 + SizeT outSize = *destLen;
2660 + *srcLen = *destLen = 0;
2661 + if (inSize < RC_INIT_SIZE)
2662 + return SZ_ERROR_INPUT_EOF;
2664 + LzmaDec_Construct(&p);
2665 + res = LzmaDec_AllocateProbs(&p, propData, propSize, alloc);
2669 + p.dicBufSize = outSize;
2674 + res = LzmaDec_DecodeToDic(&p, outSize, src, srcLen, finishMode, status);
2676 + if (res == SZ_OK && *status == LZMA_STATUS_NEEDS_MORE_INPUT)
2677 + res = SZ_ERROR_INPUT_EOF;
2679 + (*destLen) = p.dicPos;
2680 + LzmaDec_FreeProbs(&p, alloc);
2684 +++ b/jffsX-utils/lzma/LzmaEnc.c
2686 +/* LzmaEnc.c -- LZMA Encoder
2688 +Copyright (c) 1999-2008 Igor Pavlov
2689 +Read LzmaEnc.h for license options */
2691 +#if defined(SHOW_STAT) || defined(SHOW_STAT2)
2695 +#include <string.h>
2697 +#include "LzmaEnc.h"
2699 +#include "LzFind.h"
2700 +#ifdef COMPRESS_MF_MT
2701 +#include "LzFindMt.h"
2704 +/* #define SHOW_STAT */
2705 +/* #define SHOW_STAT2 */
2708 +static int ttt = 0;
2711 +#define kBlockSizeMax ((1 << LZMA_NUM_BLOCK_SIZE_BITS) - 1)
2713 +#define kBlockSize (9 << 10)
2714 +#define kUnpackBlockSize (1 << 18)
2715 +#define kMatchArraySize (1 << 21)
2716 +#define kMatchRecordMaxSize ((LZMA_MATCH_LEN_MAX * 2 + 3) * LZMA_MATCH_LEN_MAX)
2718 +#define kNumMaxDirectBits (31)
2720 +#define kNumTopBits 24
2721 +#define kTopValue ((UInt32)1 << kNumTopBits)
2723 +#define kNumBitModelTotalBits 11
2724 +#define kBitModelTotal (1 << kNumBitModelTotalBits)
2725 +#define kNumMoveBits 5
2726 +#define kProbInitValue (kBitModelTotal >> 1)
2728 +#define kNumMoveReducingBits 4
2729 +#define kNumBitPriceShiftBits 4
2730 +#define kBitPrice (1 << kNumBitPriceShiftBits)
2732 +void LzmaEncProps_Init(CLzmaEncProps *p)
2735 + p->dictSize = p->mc = 0;
2736 + p->lc = p->lp = p->pb = p->algo = p->fb = p->btMode = p->numHashBytes = p->numThreads = -1;
2737 + p->writeEndMark = 0;
2740 +void LzmaEncProps_Normalize(CLzmaEncProps *p)
2742 + int level = p->level;
2743 + if (level < 0) level = 5;
2745 + if (p->dictSize == 0) p->dictSize = (level <= 5 ? (1 << (level * 2 + 14)) : (level == 6 ? (1 << 25) : (1 << 26)));
2746 + if (p->lc < 0) p->lc = 3;
2747 + if (p->lp < 0) p->lp = 0;
2748 + if (p->pb < 0) p->pb = 2;
2749 + if (p->algo < 0) p->algo = (level < 5 ? 0 : 1);
2750 + if (p->fb < 0) p->fb = (level < 7 ? 32 : 64);
2751 + if (p->btMode < 0) p->btMode = (p->algo == 0 ? 0 : 1);
2752 + if (p->numHashBytes < 0) p->numHashBytes = 4;
2753 + if (p->mc == 0) p->mc = (16 + (p->fb >> 1)) >> (p->btMode ? 0 : 1);
2754 + if (p->numThreads < 0) p->numThreads = ((p->btMode && p->algo) ? 2 : 1);
2757 +UInt32 LzmaEncProps_GetDictSize(const CLzmaEncProps *props2)
2759 + CLzmaEncProps props = *props2;
2760 + LzmaEncProps_Normalize(&props);
2761 + return props.dictSize;
2764 +/* #define LZMA_LOG_BSR */
2765 +/* Define it for Intel's CPU */
2768 +#ifdef LZMA_LOG_BSR
2770 +#define kDicLogSizeMaxCompress 30
2772 +#define BSR2_RET(pos, res) { unsigned long i; _BitScanReverse(&i, (pos)); res = (i + i) + ((pos >> (i - 1)) & 1); }
2774 +UInt32 GetPosSlot1(UInt32 pos)
2777 + BSR2_RET(pos, res);
2780 +#define GetPosSlot2(pos, res) { BSR2_RET(pos, res); }
2781 +#define GetPosSlot(pos, res) { if (pos < 2) res = pos; else BSR2_RET(pos, res); }
2785 +#define kNumLogBits (9 + (int)sizeof(size_t) / 2)
2786 +#define kDicLogSizeMaxCompress ((kNumLogBits - 1) * 2 + 7)
2788 +static void LzmaEnc_FastPosInit(Byte *g_FastPos)
2790 + int c = 2, slotFast;
2794 + for (slotFast = 2; slotFast < kNumLogBits * 2; slotFast++)
2796 + UInt32 k = (1 << ((slotFast >> 1) - 1));
2798 + for (j = 0; j < k; j++, c++)
2799 + g_FastPos[c] = (Byte)slotFast;
2803 +#define BSR2_RET(pos, res) { UInt32 i = 6 + ((kNumLogBits - 1) & \
2804 + (0 - (((((UInt32)1 << (kNumLogBits + 6)) - 1) - pos) >> 31))); \
2805 + res = p->g_FastPos[pos >> i] + (i * 2); }
2807 +#define BSR2_RET(pos, res) { res = (pos < (1 << (kNumLogBits + 6))) ? \
2808 + p->g_FastPos[pos >> 6] + 12 : \
2809 + p->g_FastPos[pos >> (6 + kNumLogBits - 1)] + (6 + (kNumLogBits - 1)) * 2; }
2812 +#define GetPosSlot1(pos) p->g_FastPos[pos]
2813 +#define GetPosSlot2(pos, res) { BSR2_RET(pos, res); }
2814 +#define GetPosSlot(pos, res) { if (pos < kNumFullDistances) res = p->g_FastPos[pos]; else BSR2_RET(pos, res); }
2819 +#define LZMA_NUM_REPS 4
2821 +typedef unsigned CState;
2823 +typedef struct _COptimal
2836 + UInt32 backs[LZMA_NUM_REPS];
2839 +#define kNumOpts (1 << 12)
2841 +#define kNumLenToPosStates 4
2842 +#define kNumPosSlotBits 6
2843 +#define kDicLogSizeMin 0
2844 +#define kDicLogSizeMax 32
2845 +#define kDistTableSizeMax (kDicLogSizeMax * 2)
2848 +#define kNumAlignBits 4
2849 +#define kAlignTableSize (1 << kNumAlignBits)
2850 +#define kAlignMask (kAlignTableSize - 1)
2852 +#define kStartPosModelIndex 4
2853 +#define kEndPosModelIndex 14
2854 +#define kNumPosModels (kEndPosModelIndex - kStartPosModelIndex)
2856 +#define kNumFullDistances (1 << (kEndPosModelIndex / 2))
2858 +#ifdef _LZMA_PROB32
2859 +#define CLzmaProb UInt32
2861 +#define CLzmaProb UInt16
2864 +#define LZMA_PB_MAX 4
2865 +#define LZMA_LC_MAX 8
2866 +#define LZMA_LP_MAX 4
2868 +#define LZMA_NUM_PB_STATES_MAX (1 << LZMA_PB_MAX)
2871 +#define kLenNumLowBits 3
2872 +#define kLenNumLowSymbols (1 << kLenNumLowBits)
2873 +#define kLenNumMidBits 3
2874 +#define kLenNumMidSymbols (1 << kLenNumMidBits)
2875 +#define kLenNumHighBits 8
2876 +#define kLenNumHighSymbols (1 << kLenNumHighBits)
2878 +#define kLenNumSymbolsTotal (kLenNumLowSymbols + kLenNumMidSymbols + kLenNumHighSymbols)
2880 +#define LZMA_MATCH_LEN_MIN 2
2881 +#define LZMA_MATCH_LEN_MAX (LZMA_MATCH_LEN_MIN + kLenNumSymbolsTotal - 1)
2883 +#define kNumStates 12
2888 + CLzmaProb choice2;
2889 + CLzmaProb low[LZMA_NUM_PB_STATES_MAX << kLenNumLowBits];
2890 + CLzmaProb mid[LZMA_NUM_PB_STATES_MAX << kLenNumMidBits];
2891 + CLzmaProb high[kLenNumHighSymbols];
2897 + UInt32 prices[LZMA_NUM_PB_STATES_MAX][kLenNumSymbolsTotal];
2899 + UInt32 counters[LZMA_NUM_PB_STATES_MAX];
2902 +typedef struct _CRangeEnc
2911 + ISeqOutStream *outStream;
2916 +typedef struct _CSeqInStreamBuf
2918 + ISeqInStream funcTable;
2923 +static SRes MyRead(void *pp, void *data, size_t *size)
2925 + size_t curSize = *size;
2926 + CSeqInStreamBuf *p = (CSeqInStreamBuf *)pp;
2927 + if (p->rem < curSize)
2929 + memcpy(data, p->data, curSize);
2930 + p->rem -= curSize;
2931 + p->data += curSize;
2938 + CLzmaProb *litProbs;
2940 + CLzmaProb isMatch[kNumStates][LZMA_NUM_PB_STATES_MAX];
2941 + CLzmaProb isRep[kNumStates];
2942 + CLzmaProb isRepG0[kNumStates];
2943 + CLzmaProb isRepG1[kNumStates];
2944 + CLzmaProb isRepG2[kNumStates];
2945 + CLzmaProb isRep0Long[kNumStates][LZMA_NUM_PB_STATES_MAX];
2947 + CLzmaProb posSlotEncoder[kNumLenToPosStates][1 << kNumPosSlotBits];
2948 + CLzmaProb posEncoders[kNumFullDistances - kEndPosModelIndex];
2949 + CLzmaProb posAlignEncoder[1 << kNumAlignBits];
2951 + CLenPriceEnc lenEnc;
2952 + CLenPriceEnc repLenEnc;
2954 + UInt32 reps[LZMA_NUM_REPS];
2958 +typedef struct _CLzmaEnc
2960 + IMatchFinder matchFinder;
2961 + void *matchFinderObj;
2963 + #ifdef COMPRESS_MF_MT
2965 + CMatchFinderMt matchFinderMt;
2968 + CMatchFinder matchFinderBase;
2970 + #ifdef COMPRESS_MF_MT
2974 + UInt32 optimumEndIndex;
2975 + UInt32 optimumCurrentIndex;
2977 + Bool longestMatchWasFound;
2978 + UInt32 longestMatchLength;
2979 + UInt32 numDistancePairs;
2981 + COptimal opt[kNumOpts];
2983 + #ifndef LZMA_LOG_BSR
2984 + Byte g_FastPos[1 << kNumLogBits];
2987 + UInt32 ProbPrices[kBitModelTotal >> kNumMoveReducingBits];
2988 + UInt32 matchDistances[LZMA_MATCH_LEN_MAX * 2 + 2 + 1];
2989 + UInt32 numFastBytes;
2990 + UInt32 additionalOffset;
2991 + UInt32 reps[LZMA_NUM_REPS];
2994 + UInt32 posSlotPrices[kNumLenToPosStates][kDistTableSizeMax];
2995 + UInt32 distancesPrices[kNumLenToPosStates][kNumFullDistances];
2996 + UInt32 alignPrices[kAlignTableSize];
2997 + UInt32 alignPriceCount;
2999 + UInt32 distTableSize;
3001 + unsigned lc, lp, pb;
3002 + unsigned lpMask, pbMask;
3004 + CLzmaProb *litProbs;
3006 + CLzmaProb isMatch[kNumStates][LZMA_NUM_PB_STATES_MAX];
3007 + CLzmaProb isRep[kNumStates];
3008 + CLzmaProb isRepG0[kNumStates];
3009 + CLzmaProb isRepG1[kNumStates];
3010 + CLzmaProb isRepG2[kNumStates];
3011 + CLzmaProb isRep0Long[kNumStates][LZMA_NUM_PB_STATES_MAX];
3013 + CLzmaProb posSlotEncoder[kNumLenToPosStates][1 << kNumPosSlotBits];
3014 + CLzmaProb posEncoders[kNumFullDistances - kEndPosModelIndex];
3015 + CLzmaProb posAlignEncoder[1 << kNumAlignBits];
3017 + CLenPriceEnc lenEnc;
3018 + CLenPriceEnc repLenEnc;
3026 + Bool writeEndMark;
3028 + UInt32 matchPriceCount;
3034 + UInt32 matchFinderCycles;
3036 + ISeqInStream *inStream;
3037 + CSeqInStreamBuf seqBufInStream;
3039 + CSaveState saveState;
3042 +static void LzmaEnc_SaveState(CLzmaEncHandle pp)
3044 + CLzmaEnc *p = (CLzmaEnc *)pp;
3045 + CSaveState *dest = &p->saveState;
3047 + dest->lenEnc = p->lenEnc;
3048 + dest->repLenEnc = p->repLenEnc;
3049 + dest->state = p->state;
3051 + for (i = 0; i < kNumStates; i++)
3053 + memcpy(dest->isMatch[i], p->isMatch[i], sizeof(p->isMatch[i]));
3054 + memcpy(dest->isRep0Long[i], p->isRep0Long[i], sizeof(p->isRep0Long[i]));
3056 + for (i = 0; i < kNumLenToPosStates; i++)
3057 + memcpy(dest->posSlotEncoder[i], p->posSlotEncoder[i], sizeof(p->posSlotEncoder[i]));
3058 + memcpy(dest->isRep, p->isRep, sizeof(p->isRep));
3059 + memcpy(dest->isRepG0, p->isRepG0, sizeof(p->isRepG0));
3060 + memcpy(dest->isRepG1, p->isRepG1, sizeof(p->isRepG1));
3061 + memcpy(dest->isRepG2, p->isRepG2, sizeof(p->isRepG2));
3062 + memcpy(dest->posEncoders, p->posEncoders, sizeof(p->posEncoders));
3063 + memcpy(dest->posAlignEncoder, p->posAlignEncoder, sizeof(p->posAlignEncoder));
3064 + memcpy(dest->reps, p->reps, sizeof(p->reps));
3065 + memcpy(dest->litProbs, p->litProbs, (0x300 << p->lclp) * sizeof(CLzmaProb));
3068 +static void LzmaEnc_RestoreState(CLzmaEncHandle pp)
3070 + CLzmaEnc *dest = (CLzmaEnc *)pp;
3071 + const CSaveState *p = &dest->saveState;
3073 + dest->lenEnc = p->lenEnc;
3074 + dest->repLenEnc = p->repLenEnc;
3075 + dest->state = p->state;
3077 + for (i = 0; i < kNumStates; i++)
3079 + memcpy(dest->isMatch[i], p->isMatch[i], sizeof(p->isMatch[i]));
3080 + memcpy(dest->isRep0Long[i], p->isRep0Long[i], sizeof(p->isRep0Long[i]));
3082 + for (i = 0; i < kNumLenToPosStates; i++)
3083 + memcpy(dest->posSlotEncoder[i], p->posSlotEncoder[i], sizeof(p->posSlotEncoder[i]));
3084 + memcpy(dest->isRep, p->isRep, sizeof(p->isRep));
3085 + memcpy(dest->isRepG0, p->isRepG0, sizeof(p->isRepG0));
3086 + memcpy(dest->isRepG1, p->isRepG1, sizeof(p->isRepG1));
3087 + memcpy(dest->isRepG2, p->isRepG2, sizeof(p->isRepG2));
3088 + memcpy(dest->posEncoders, p->posEncoders, sizeof(p->posEncoders));
3089 + memcpy(dest->posAlignEncoder, p->posAlignEncoder, sizeof(p->posAlignEncoder));
3090 + memcpy(dest->reps, p->reps, sizeof(p->reps));
3091 + memcpy(dest->litProbs, p->litProbs, (0x300 << dest->lclp) * sizeof(CLzmaProb));
3094 +SRes LzmaEnc_SetProps(CLzmaEncHandle pp, const CLzmaEncProps *props2)
3096 + CLzmaEnc *p = (CLzmaEnc *)pp;
3097 + CLzmaEncProps props = *props2;
3098 + LzmaEncProps_Normalize(&props);
3100 + if (props.lc > LZMA_LC_MAX || props.lp > LZMA_LP_MAX || props.pb > LZMA_PB_MAX ||
3101 + props.dictSize > (1 << kDicLogSizeMaxCompress) || props.dictSize > (1 << 30))
3102 + return SZ_ERROR_PARAM;
3103 + p->dictSize = props.dictSize;
3104 + p->matchFinderCycles = props.mc;
3106 + unsigned fb = props.fb;
3109 + if (fb > LZMA_MATCH_LEN_MAX)
3110 + fb = LZMA_MATCH_LEN_MAX;
3111 + p->numFastBytes = fb;
3116 + p->fastMode = (props.algo == 0);
3117 + p->matchFinderBase.btMode = props.btMode;
3119 + UInt32 numHashBytes = 4;
3122 + if (props.numHashBytes < 2)
3124 + else if (props.numHashBytes < 4)
3125 + numHashBytes = props.numHashBytes;
3127 + p->matchFinderBase.numHashBytes = numHashBytes;
3130 + p->matchFinderBase.cutValue = props.mc;
3132 + p->writeEndMark = props.writeEndMark;
3134 + #ifdef COMPRESS_MF_MT
3136 + if (newMultiThread != _multiThread)
3138 + ReleaseMatchFinder();
3139 + _multiThread = newMultiThread;
3142 + p->multiThread = (props.numThreads > 1);
3148 +static const int kLiteralNextStates[kNumStates] = {0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 4, 5};
3149 +static const int kMatchNextStates[kNumStates] = {7, 7, 7, 7, 7, 7, 7, 10, 10, 10, 10, 10};
3150 +static const int kRepNextStates[kNumStates] = {8, 8, 8, 8, 8, 8, 8, 11, 11, 11, 11, 11};
3151 +static const int kShortRepNextStates[kNumStates]= {9, 9, 9, 9, 9, 9, 9, 11, 11, 11, 11, 11};
3154 + void UpdateChar() { Index = kLiteralNextStates[Index]; }
3155 + void UpdateMatch() { Index = kMatchNextStates[Index]; }
3156 + void UpdateRep() { Index = kRepNextStates[Index]; }
3157 + void UpdateShortRep() { Index = kShortRepNextStates[Index]; }
3160 +#define IsCharState(s) ((s) < 7)
3163 +#define GetLenToPosState(len) (((len) < kNumLenToPosStates + 1) ? (len) - 2 : kNumLenToPosStates - 1)
3165 +#define kInfinityPrice (1 << 30)
3167 +static void RangeEnc_Construct(CRangeEnc *p)
3173 +#define RangeEnc_GetProcessed(p) ((p)->processed + ((p)->buf - (p)->bufBase) + (p)->cacheSize)
3175 +#define RC_BUF_SIZE (1 << 16)
3176 +static int RangeEnc_Alloc(CRangeEnc *p, ISzAlloc *alloc)
3178 + if (p->bufBase == 0)
3180 + p->bufBase = (Byte *)alloc->Alloc(alloc, RC_BUF_SIZE);
3181 + if (p->bufBase == 0)
3183 + p->bufLim = p->bufBase + RC_BUF_SIZE;
3188 +static void RangeEnc_Free(CRangeEnc *p, ISzAlloc *alloc)
3190 + alloc->Free(alloc, p->bufBase);
3194 +static void RangeEnc_Init(CRangeEnc *p)
3196 + /* Stream.Init(); */
3198 + p->range = 0xFFFFFFFF;
3202 + p->buf = p->bufBase;
3208 +static void RangeEnc_FlushStream(CRangeEnc *p)
3211 + if (p->res != SZ_OK)
3213 + num = p->buf - p->bufBase;
3214 + if (num != p->outStream->Write(p->outStream, p->bufBase, num))
3215 + p->res = SZ_ERROR_WRITE;
3216 + p->processed += num;
3217 + p->buf = p->bufBase;
3220 +static void MY_FAST_CALL RangeEnc_ShiftLow(CRangeEnc *p)
3222 + if ((UInt32)p->low < (UInt32)0xFF000000 || (int)(p->low >> 32) != 0)
3224 + Byte temp = p->cache;
3227 + Byte *buf = p->buf;
3228 + *buf++ = (Byte)(temp + (Byte)(p->low >> 32));
3230 + if (buf == p->bufLim)
3231 + RangeEnc_FlushStream(p);
3234 + while (--p->cacheSize != 0);
3235 + p->cache = (Byte)((UInt32)p->low >> 24);
3238 + p->low = (UInt32)p->low << 8;
3241 +static void RangeEnc_FlushData(CRangeEnc *p)
3244 + for (i = 0; i < 5; i++)
3245 + RangeEnc_ShiftLow(p);
3248 +static void RangeEnc_EncodeDirectBits(CRangeEnc *p, UInt32 value, int numBits)
3253 + p->low += p->range & (0 - ((value >> --numBits) & 1));
3254 + if (p->range < kTopValue)
3257 + RangeEnc_ShiftLow(p);
3260 + while (numBits != 0);
3263 +static void RangeEnc_EncodeBit(CRangeEnc *p, CLzmaProb *prob, UInt32 symbol)
3265 + UInt32 ttt = *prob;
3266 + UInt32 newBound = (p->range >> kNumBitModelTotalBits) * ttt;
3269 + p->range = newBound;
3270 + ttt += (kBitModelTotal - ttt) >> kNumMoveBits;
3274 + p->low += newBound;
3275 + p->range -= newBound;
3276 + ttt -= ttt >> kNumMoveBits;
3278 + *prob = (CLzmaProb)ttt;
3279 + if (p->range < kTopValue)
3282 + RangeEnc_ShiftLow(p);
3286 +static void LitEnc_Encode(CRangeEnc *p, CLzmaProb *probs, UInt32 symbol)
3291 + RangeEnc_EncodeBit(p, probs + (symbol >> 8), (symbol >> 7) & 1);
3294 + while (symbol < 0x10000);
3297 +static void LitEnc_EncodeMatched(CRangeEnc *p, CLzmaProb *probs, UInt32 symbol, UInt32 matchByte)
3299 + UInt32 offs = 0x100;
3304 + RangeEnc_EncodeBit(p, probs + (offs + (matchByte & offs) + (symbol >> 8)), (symbol >> 7) & 1);
3306 + offs &= ~(matchByte ^ symbol);
3308 + while (symbol < 0x10000);
3311 +static void LzmaEnc_InitPriceTables(UInt32 *ProbPrices)
3314 + for (i = (1 << kNumMoveReducingBits) / 2; i < kBitModelTotal; i += (1 << kNumMoveReducingBits))
3316 + const int kCyclesBits = kNumBitPriceShiftBits;
3318 + UInt32 bitCount = 0;
3320 + for (j = 0; j < kCyclesBits; j++)
3324 + while (w >= ((UInt32)1 << 16))
3330 + ProbPrices[i >> kNumMoveReducingBits] = ((kNumBitModelTotalBits << kCyclesBits) - 15 - bitCount);
3335 +#define GET_PRICE(prob, symbol) \
3336 + p->ProbPrices[((prob) ^ (((-(int)(symbol))) & (kBitModelTotal - 1))) >> kNumMoveReducingBits];
3338 +#define GET_PRICEa(prob, symbol) \
3339 + ProbPrices[((prob) ^ ((-((int)(symbol))) & (kBitModelTotal - 1))) >> kNumMoveReducingBits];
3341 +#define GET_PRICE_0(prob) p->ProbPrices[(prob) >> kNumMoveReducingBits]
3342 +#define GET_PRICE_1(prob) p->ProbPrices[((prob) ^ (kBitModelTotal - 1)) >> kNumMoveReducingBits]
3344 +#define GET_PRICE_0a(prob) ProbPrices[(prob) >> kNumMoveReducingBits]
3345 +#define GET_PRICE_1a(prob) ProbPrices[((prob) ^ (kBitModelTotal - 1)) >> kNumMoveReducingBits]
3347 +static UInt32 LitEnc_GetPrice(const CLzmaProb *probs, UInt32 symbol, UInt32 *ProbPrices)
3353 + price += GET_PRICEa(probs[symbol >> 8], (symbol >> 7) & 1);
3356 + while (symbol < 0x10000);
3360 +static UInt32 LitEnc_GetPriceMatched(const CLzmaProb *probs, UInt32 symbol, UInt32 matchByte, UInt32 *ProbPrices)
3363 + UInt32 offs = 0x100;
3368 + price += GET_PRICEa(probs[offs + (matchByte & offs) + (symbol >> 8)], (symbol >> 7) & 1);
3370 + offs &= ~(matchByte ^ symbol);
3372 + while (symbol < 0x10000);
3377 +static void RcTree_Encode(CRangeEnc *rc, CLzmaProb *probs, int numBitLevels, UInt32 symbol)
3381 + for (i = numBitLevels; i != 0 ;)
3385 + bit = (symbol >> i) & 1;
3386 + RangeEnc_EncodeBit(rc, probs + m, bit);
3387 + m = (m << 1) | bit;
3391 +static void RcTree_ReverseEncode(CRangeEnc *rc, CLzmaProb *probs, int numBitLevels, UInt32 symbol)
3395 + for (i = 0; i < numBitLevels; i++)
3397 + UInt32 bit = symbol & 1;
3398 + RangeEnc_EncodeBit(rc, probs + m, bit);
3399 + m = (m << 1) | bit;
3404 +static UInt32 RcTree_GetPrice(const CLzmaProb *probs, int numBitLevels, UInt32 symbol, UInt32 *ProbPrices)
3407 + symbol |= (1 << numBitLevels);
3408 + while (symbol != 1)
3410 + price += GET_PRICEa(probs[symbol >> 1], symbol & 1);
3416 +static UInt32 RcTree_ReverseGetPrice(const CLzmaProb *probs, int numBitLevels, UInt32 symbol, UInt32 *ProbPrices)
3421 + for (i = numBitLevels; i != 0; i--)
3423 + UInt32 bit = symbol & 1;
3425 + price += GET_PRICEa(probs[m], bit);
3426 + m = (m << 1) | bit;
3432 +static void LenEnc_Init(CLenEnc *p)
3435 + p->choice = p->choice2 = kProbInitValue;
3436 + for (i = 0; i < (LZMA_NUM_PB_STATES_MAX << kLenNumLowBits); i++)
3437 + p->low[i] = kProbInitValue;
3438 + for (i = 0; i < (LZMA_NUM_PB_STATES_MAX << kLenNumMidBits); i++)
3439 + p->mid[i] = kProbInitValue;
3440 + for (i = 0; i < kLenNumHighSymbols; i++)
3441 + p->high[i] = kProbInitValue;
3444 +static void LenEnc_Encode(CLenEnc *p, CRangeEnc *rc, UInt32 symbol, UInt32 posState)
3446 + if (symbol < kLenNumLowSymbols)
3448 + RangeEnc_EncodeBit(rc, &p->choice, 0);
3449 + RcTree_Encode(rc, p->low + (posState << kLenNumLowBits), kLenNumLowBits, symbol);
3453 + RangeEnc_EncodeBit(rc, &p->choice, 1);
3454 + if (symbol < kLenNumLowSymbols + kLenNumMidSymbols)
3456 + RangeEnc_EncodeBit(rc, &p->choice2, 0);
3457 + RcTree_Encode(rc, p->mid + (posState << kLenNumMidBits), kLenNumMidBits, symbol - kLenNumLowSymbols);
3461 + RangeEnc_EncodeBit(rc, &p->choice2, 1);
3462 + RcTree_Encode(rc, p->high, kLenNumHighBits, symbol - kLenNumLowSymbols - kLenNumMidSymbols);
3467 +static void LenEnc_SetPrices(CLenEnc *p, UInt32 posState, UInt32 numSymbols, UInt32 *prices, UInt32 *ProbPrices)
3469 + UInt32 a0 = GET_PRICE_0a(p->choice);
3470 + UInt32 a1 = GET_PRICE_1a(p->choice);
3471 + UInt32 b0 = a1 + GET_PRICE_0a(p->choice2);
3472 + UInt32 b1 = a1 + GET_PRICE_1a(p->choice2);
3474 + for (i = 0; i < kLenNumLowSymbols; i++)
3476 + if (i >= numSymbols)
3478 + prices[i] = a0 + RcTree_GetPrice(p->low + (posState << kLenNumLowBits), kLenNumLowBits, i, ProbPrices);
3480 + for (; i < kLenNumLowSymbols + kLenNumMidSymbols; i++)
3482 + if (i >= numSymbols)
3484 + prices[i] = b0 + RcTree_GetPrice(p->mid + (posState << kLenNumMidBits), kLenNumMidBits, i - kLenNumLowSymbols, ProbPrices);
3486 + for (; i < numSymbols; i++)
3487 + prices[i] = b1 + RcTree_GetPrice(p->high, kLenNumHighBits, i - kLenNumLowSymbols - kLenNumMidSymbols, ProbPrices);
3490 +static void MY_FAST_CALL LenPriceEnc_UpdateTable(CLenPriceEnc *p, UInt32 posState, UInt32 *ProbPrices)
3492 + LenEnc_SetPrices(&p->p, posState, p->tableSize, p->prices[posState], ProbPrices);
3493 + p->counters[posState] = p->tableSize;
3496 +static void LenPriceEnc_UpdateTables(CLenPriceEnc *p, UInt32 numPosStates, UInt32 *ProbPrices)
3499 + for (posState = 0; posState < numPosStates; posState++)
3500 + LenPriceEnc_UpdateTable(p, posState, ProbPrices);
3503 +static void LenEnc_Encode2(CLenPriceEnc *p, CRangeEnc *rc, UInt32 symbol, UInt32 posState, Bool updatePrice, UInt32 *ProbPrices)
3505 + LenEnc_Encode(&p->p, rc, symbol, posState);
3507 + if (--p->counters[posState] == 0)
3508 + LenPriceEnc_UpdateTable(p, posState, ProbPrices);
3514 +static void MovePos(CLzmaEnc *p, UInt32 num)
3518 + printf("\n MovePos %d", num);
3522 + p->additionalOffset += num;
3523 + p->matchFinder.Skip(p->matchFinderObj, num);
3527 +static UInt32 ReadMatchDistances(CLzmaEnc *p, UInt32 *numDistancePairsRes)
3529 + UInt32 lenRes = 0, numDistancePairs;
3530 + numDistancePairs = p->matchFinder.GetMatches(p->matchFinderObj, p->matchDistances);
3532 + printf("\n i = %d numPairs = %d ", ttt, numDistancePairs / 2);
3539 + for (i = 0; i < numDistancePairs; i += 2)
3540 + printf("%2d %6d | ", p->matchDistances[i], p->matchDistances[i + 1]);
3543 + if (numDistancePairs > 0)
3545 + lenRes = p->matchDistances[numDistancePairs - 2];
3546 + if (lenRes == p->numFastBytes)
3548 + UInt32 numAvail = p->matchFinder.GetNumAvailableBytes(p->matchFinderObj) + 1;
3549 + const Byte *pby = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - 1;
3550 + UInt32 distance = p->matchDistances[numDistancePairs - 1] + 1;
3551 + if (numAvail > LZMA_MATCH_LEN_MAX)
3552 + numAvail = LZMA_MATCH_LEN_MAX;
3555 + const Byte *pby2 = pby - distance;
3556 + for (; lenRes < numAvail && pby[lenRes] == pby2[lenRes]; lenRes++);
3560 + p->additionalOffset++;
3561 + *numDistancePairsRes = numDistancePairs;
3566 +#define MakeAsChar(p) (p)->backPrev = (UInt32)(-1); (p)->prev1IsChar = False;
3567 +#define MakeAsShortRep(p) (p)->backPrev = 0; (p)->prev1IsChar = False;
3568 +#define IsShortRep(p) ((p)->backPrev == 0)
3570 +static UInt32 GetRepLen1Price(CLzmaEnc *p, UInt32 state, UInt32 posState)
3573 + GET_PRICE_0(p->isRepG0[state]) +
3574 + GET_PRICE_0(p->isRep0Long[state][posState]);
3577 +static UInt32 GetPureRepPrice(CLzmaEnc *p, UInt32 repIndex, UInt32 state, UInt32 posState)
3580 + if (repIndex == 0)
3582 + price = GET_PRICE_0(p->isRepG0[state]);
3583 + price += GET_PRICE_1(p->isRep0Long[state][posState]);
3587 + price = GET_PRICE_1(p->isRepG0[state]);
3588 + if (repIndex == 1)
3589 + price += GET_PRICE_0(p->isRepG1[state]);
3592 + price += GET_PRICE_1(p->isRepG1[state]);
3593 + price += GET_PRICE(p->isRepG2[state], repIndex - 2);
3599 +static UInt32 GetRepPrice(CLzmaEnc *p, UInt32 repIndex, UInt32 len, UInt32 state, UInt32 posState)
3601 + return p->repLenEnc.prices[posState][len - LZMA_MATCH_LEN_MIN] +
3602 + GetPureRepPrice(p, repIndex, state, posState);
3605 +static UInt32 Backward(CLzmaEnc *p, UInt32 *backRes, UInt32 cur)
3607 + UInt32 posMem = p->opt[cur].posPrev;
3608 + UInt32 backMem = p->opt[cur].backPrev;
3609 + p->optimumEndIndex = cur;
3612 + if (p->opt[cur].prev1IsChar)
3614 + MakeAsChar(&p->opt[posMem])
3615 + p->opt[posMem].posPrev = posMem - 1;
3616 + if (p->opt[cur].prev2)
3618 + p->opt[posMem - 1].prev1IsChar = False;
3619 + p->opt[posMem - 1].posPrev = p->opt[cur].posPrev2;
3620 + p->opt[posMem - 1].backPrev = p->opt[cur].backPrev2;
3624 + UInt32 posPrev = posMem;
3625 + UInt32 backCur = backMem;
3627 + backMem = p->opt[posPrev].backPrev;
3628 + posMem = p->opt[posPrev].posPrev;
3630 + p->opt[posPrev].backPrev = backCur;
3631 + p->opt[posPrev].posPrev = cur;
3636 + *backRes = p->opt[0].backPrev;
3637 + p->optimumCurrentIndex = p->opt[0].posPrev;
3638 + return p->optimumCurrentIndex;
3641 +#define LIT_PROBS(pos, prevByte) (p->litProbs + ((((pos) & p->lpMask) << p->lc) + ((prevByte) >> (8 - p->lc))) * 0x300)
3643 +static UInt32 GetOptimum(CLzmaEnc *p, UInt32 position, UInt32 *backRes)
3645 + UInt32 numAvailableBytes, lenMain, numDistancePairs;
3647 + UInt32 reps[LZMA_NUM_REPS];
3648 + UInt32 repLens[LZMA_NUM_REPS];
3649 + UInt32 repMaxIndex, i;
3650 + UInt32 *matchDistances;
3651 + Byte currentByte, matchByte;
3653 + UInt32 matchPrice, repMatchPrice;
3656 + UInt32 normalMatchPrice;
3658 + if (p->optimumEndIndex != p->optimumCurrentIndex)
3660 + const COptimal *opt = &p->opt[p->optimumCurrentIndex];
3661 + UInt32 lenRes = opt->posPrev - p->optimumCurrentIndex;
3662 + *backRes = opt->backPrev;
3663 + p->optimumCurrentIndex = opt->posPrev;
3666 + p->optimumCurrentIndex = p->optimumEndIndex = 0;
3668 + numAvailableBytes = p->matchFinder.GetNumAvailableBytes(p->matchFinderObj);
3670 + if (!p->longestMatchWasFound)
3672 + lenMain = ReadMatchDistances(p, &numDistancePairs);
3676 + lenMain = p->longestMatchLength;
3677 + numDistancePairs = p->numDistancePairs;
3678 + p->longestMatchWasFound = False;
3681 + data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - 1;
3682 + if (numAvailableBytes < 2)
3684 + *backRes = (UInt32)(-1);
3687 + if (numAvailableBytes > LZMA_MATCH_LEN_MAX)
3688 + numAvailableBytes = LZMA_MATCH_LEN_MAX;
3691 + for (i = 0; i < LZMA_NUM_REPS; i++)
3694 + const Byte *data2;
3695 + reps[i] = p->reps[i];
3696 + data2 = data - (reps[i] + 1);
3697 + if (data[0] != data2[0] || data[1] != data2[1])
3702 + for (lenTest = 2; lenTest < numAvailableBytes && data[lenTest] == data2[lenTest]; lenTest++);
3703 + repLens[i] = lenTest;
3704 + if (lenTest > repLens[repMaxIndex])
3707 + if (repLens[repMaxIndex] >= p->numFastBytes)
3710 + *backRes = repMaxIndex;
3711 + lenRes = repLens[repMaxIndex];
3712 + MovePos(p, lenRes - 1);
3716 + matchDistances = p->matchDistances;
3717 + if (lenMain >= p->numFastBytes)
3719 + *backRes = matchDistances[numDistancePairs - 1] + LZMA_NUM_REPS;
3720 + MovePos(p, lenMain - 1);
3723 + currentByte = *data;
3724 + matchByte = *(data - (reps[0] + 1));
3726 + if (lenMain < 2 && currentByte != matchByte && repLens[repMaxIndex] < 2)
3728 + *backRes = (UInt32)-1;
3732 + p->opt[0].state = (CState)p->state;
3734 + posState = (position & p->pbMask);
3737 + const CLzmaProb *probs = LIT_PROBS(position, *(data - 1));
3738 + p->opt[1].price = GET_PRICE_0(p->isMatch[p->state][posState]) +
3739 + (!IsCharState(p->state) ?
3740 + LitEnc_GetPriceMatched(probs, currentByte, matchByte, p->ProbPrices) :
3741 + LitEnc_GetPrice(probs, currentByte, p->ProbPrices));
3744 + MakeAsChar(&p->opt[1]);
3746 + matchPrice = GET_PRICE_1(p->isMatch[p->state][posState]);
3747 + repMatchPrice = matchPrice + GET_PRICE_1(p->isRep[p->state]);
3749 + if (matchByte == currentByte)
3751 + UInt32 shortRepPrice = repMatchPrice + GetRepLen1Price(p, p->state, posState);
3752 + if (shortRepPrice < p->opt[1].price)
3754 + p->opt[1].price = shortRepPrice;
3755 + MakeAsShortRep(&p->opt[1]);
3758 + lenEnd = ((lenMain >= repLens[repMaxIndex]) ? lenMain : repLens[repMaxIndex]);
3762 + *backRes = p->opt[1].backPrev;
3766 + p->opt[1].posPrev = 0;
3767 + for (i = 0; i < LZMA_NUM_REPS; i++)
3768 + p->opt[0].backs[i] = reps[i];
3772 + p->opt[len--].price = kInfinityPrice;
3775 + for (i = 0; i < LZMA_NUM_REPS; i++)
3777 + UInt32 repLen = repLens[i];
3781 + price = repMatchPrice + GetPureRepPrice(p, i, p->state, posState);
3784 + UInt32 curAndLenPrice = price + p->repLenEnc.prices[posState][repLen - 2];
3785 + COptimal *opt = &p->opt[repLen];
3786 + if (curAndLenPrice < opt->price)
3788 + opt->price = curAndLenPrice;
3790 + opt->backPrev = i;
3791 + opt->prev1IsChar = False;
3794 + while (--repLen >= 2);
3797 + normalMatchPrice = matchPrice + GET_PRICE_0(p->isRep[p->state]);
3799 + len = ((repLens[0] >= 2) ? repLens[0] + 1 : 2);
3800 + if (len <= lenMain)
3803 + while (len > matchDistances[offs])
3808 + UInt32 distance = matchDistances[offs + 1];
3810 + UInt32 curAndLenPrice = normalMatchPrice + p->lenEnc.prices[posState][len - LZMA_MATCH_LEN_MIN];
3811 + UInt32 lenToPosState = GetLenToPosState(len);
3812 + if (distance < kNumFullDistances)
3813 + curAndLenPrice += p->distancesPrices[lenToPosState][distance];
3817 + GetPosSlot2(distance, slot);
3818 + curAndLenPrice += p->alignPrices[distance & kAlignMask] + p->posSlotPrices[lenToPosState][slot];
3820 + opt = &p->opt[len];
3821 + if (curAndLenPrice < opt->price)
3823 + opt->price = curAndLenPrice;
3825 + opt->backPrev = distance + LZMA_NUM_REPS;
3826 + opt->prev1IsChar = False;
3828 + if (len == matchDistances[offs])
3831 + if (offs == numDistancePairs)
3840 + if (position >= 0)
3843 + printf("\n pos = %4X", position);
3844 + for (i = cur; i <= lenEnd; i++)
3845 + printf("\nprice[%4X] = %d", position - cur + i, p->opt[i].price);
3851 + UInt32 numAvailableBytesFull, newLen, numDistancePairs;
3858 + Byte currentByte, matchByte;
3860 + UInt32 curAnd1Price;
3861 + COptimal *nextOpt;
3862 + UInt32 matchPrice, repMatchPrice;
3863 + UInt32 numAvailableBytes;
3867 + if (cur == lenEnd)
3868 + return Backward(p, backRes, cur);
3870 + numAvailableBytesFull = p->matchFinder.GetNumAvailableBytes(p->matchFinderObj);
3871 + newLen = ReadMatchDistances(p, &numDistancePairs);
3872 + if (newLen >= p->numFastBytes)
3874 + p->numDistancePairs = numDistancePairs;
3875 + p->longestMatchLength = newLen;
3876 + p->longestMatchWasFound = True;
3877 + return Backward(p, backRes, cur);
3880 + curOpt = &p->opt[cur];
3881 + posPrev = curOpt->posPrev;
3882 + if (curOpt->prev1IsChar)
3885 + if (curOpt->prev2)
3887 + state = p->opt[curOpt->posPrev2].state;
3888 + if (curOpt->backPrev2 < LZMA_NUM_REPS)
3889 + state = kRepNextStates[state];
3891 + state = kMatchNextStates[state];
3894 + state = p->opt[posPrev].state;
3895 + state = kLiteralNextStates[state];
3898 + state = p->opt[posPrev].state;
3899 + if (posPrev == cur - 1)
3901 + if (IsShortRep(curOpt))
3902 + state = kShortRepNextStates[state];
3904 + state = kLiteralNextStates[state];
3909 + const COptimal *prevOpt;
3910 + if (curOpt->prev1IsChar && curOpt->prev2)
3912 + posPrev = curOpt->posPrev2;
3913 + pos = curOpt->backPrev2;
3914 + state = kRepNextStates[state];
3918 + pos = curOpt->backPrev;
3919 + if (pos < LZMA_NUM_REPS)
3920 + state = kRepNextStates[state];
3922 + state = kMatchNextStates[state];
3924 + prevOpt = &p->opt[posPrev];
3925 + if (pos < LZMA_NUM_REPS)
3928 + reps[0] = prevOpt->backs[pos];
3929 + for (i = 1; i <= pos; i++)
3930 + reps[i] = prevOpt->backs[i - 1];
3931 + for (; i < LZMA_NUM_REPS; i++)
3932 + reps[i] = prevOpt->backs[i];
3937 + reps[0] = (pos - LZMA_NUM_REPS);
3938 + for (i = 1; i < LZMA_NUM_REPS; i++)
3939 + reps[i] = prevOpt->backs[i - 1];
3942 + curOpt->state = (CState)state;
3944 + curOpt->backs[0] = reps[0];
3945 + curOpt->backs[1] = reps[1];
3946 + curOpt->backs[2] = reps[2];
3947 + curOpt->backs[3] = reps[3];
3949 + curPrice = curOpt->price;
3950 + nextIsChar = False;
3951 + data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - 1;
3952 + currentByte = *data;
3953 + matchByte = *(data - (reps[0] + 1));
3955 + posState = (position & p->pbMask);
3957 + curAnd1Price = curPrice + GET_PRICE_0(p->isMatch[state][posState]);
3959 + const CLzmaProb *probs = LIT_PROBS(position, *(data - 1));
3961 + (!IsCharState(state) ?
3962 + LitEnc_GetPriceMatched(probs, currentByte, matchByte, p->ProbPrices) :
3963 + LitEnc_GetPrice(probs, currentByte, p->ProbPrices));
3966 + nextOpt = &p->opt[cur + 1];
3968 + if (curAnd1Price < nextOpt->price)
3970 + nextOpt->price = curAnd1Price;
3971 + nextOpt->posPrev = cur;
3972 + MakeAsChar(nextOpt);
3973 + nextIsChar = True;
3976 + matchPrice = curPrice + GET_PRICE_1(p->isMatch[state][posState]);
3977 + repMatchPrice = matchPrice + GET_PRICE_1(p->isRep[state]);
3979 + if (matchByte == currentByte && !(nextOpt->posPrev < cur && nextOpt->backPrev == 0))
3981 + UInt32 shortRepPrice = repMatchPrice + GetRepLen1Price(p, state, posState);
3982 + if (shortRepPrice <= nextOpt->price)
3984 + nextOpt->price = shortRepPrice;
3985 + nextOpt->posPrev = cur;
3986 + MakeAsShortRep(nextOpt);
3987 + nextIsChar = True;
3992 + UInt32 temp = kNumOpts - 1 - cur;
3993 + if (temp < numAvailableBytesFull)
3994 + numAvailableBytesFull = temp;
3996 + numAvailableBytes = numAvailableBytesFull;
3998 + if (numAvailableBytes < 2)
4000 + if (numAvailableBytes > p->numFastBytes)
4001 + numAvailableBytes = p->numFastBytes;
4002 + if (!nextIsChar && matchByte != currentByte) /* speed optimization */
4004 + /* try Literal + rep0 */
4007 + const Byte *data2 = data - (reps[0] + 1);
4008 + UInt32 limit = p->numFastBytes + 1;
4009 + if (limit > numAvailableBytesFull)
4010 + limit = numAvailableBytesFull;
4012 + for (temp = 1; temp < limit && data[temp] == data2[temp]; temp++);
4013 + lenTest2 = temp - 1;
4014 + if (lenTest2 >= 2)
4016 + UInt32 state2 = kLiteralNextStates[state];
4017 + UInt32 posStateNext = (position + 1) & p->pbMask;
4018 + UInt32 nextRepMatchPrice = curAnd1Price +
4019 + GET_PRICE_1(p->isMatch[state2][posStateNext]) +
4020 + GET_PRICE_1(p->isRep[state2]);
4021 + /* for (; lenTest2 >= 2; lenTest2--) */
4023 + UInt32 curAndLenPrice;
4025 + UInt32 offset = cur + 1 + lenTest2;
4026 + while (lenEnd < offset)
4027 + p->opt[++lenEnd].price = kInfinityPrice;
4028 + curAndLenPrice = nextRepMatchPrice + GetRepPrice(p, 0, lenTest2, state2, posStateNext);
4029 + opt = &p->opt[offset];
4030 + if (curAndLenPrice < opt->price)
4032 + opt->price = curAndLenPrice;
4033 + opt->posPrev = cur + 1;
4034 + opt->backPrev = 0;
4035 + opt->prev1IsChar = True;
4036 + opt->prev2 = False;
4042 + startLen = 2; /* speed optimization */
4045 + for (repIndex = 0; repIndex < LZMA_NUM_REPS; repIndex++)
4048 + UInt32 lenTestTemp;
4050 + const Byte *data2 = data - (reps[repIndex] + 1);
4051 + if (data[0] != data2[0] || data[1] != data2[1])
4053 + for (lenTest = 2; lenTest < numAvailableBytes && data[lenTest] == data2[lenTest]; lenTest++);
4054 + while (lenEnd < cur + lenTest)
4055 + p->opt[++lenEnd].price = kInfinityPrice;
4056 + lenTestTemp = lenTest;
4057 + price = repMatchPrice + GetPureRepPrice(p, repIndex, state, posState);
4060 + UInt32 curAndLenPrice = price + p->repLenEnc.prices[posState][lenTest - 2];
4061 + COptimal *opt = &p->opt[cur + lenTest];
4062 + if (curAndLenPrice < opt->price)
4064 + opt->price = curAndLenPrice;
4065 + opt->posPrev = cur;
4066 + opt->backPrev = repIndex;
4067 + opt->prev1IsChar = False;
4070 + while (--lenTest >= 2);
4071 + lenTest = lenTestTemp;
4073 + if (repIndex == 0)
4074 + startLen = lenTest + 1;
4076 + /* if (_maxMode) */
4078 + UInt32 lenTest2 = lenTest + 1;
4079 + UInt32 limit = lenTest2 + p->numFastBytes;
4080 + UInt32 nextRepMatchPrice;
4081 + if (limit > numAvailableBytesFull)
4082 + limit = numAvailableBytesFull;
4083 + for (; lenTest2 < limit && data[lenTest2] == data2[lenTest2]; lenTest2++);
4084 + lenTest2 -= lenTest + 1;
4085 + if (lenTest2 >= 2)
4087 + UInt32 state2 = kRepNextStates[state];
4088 + UInt32 posStateNext = (position + lenTest) & p->pbMask;
4089 + UInt32 curAndLenCharPrice =
4090 + price + p->repLenEnc.prices[posState][lenTest - 2] +
4091 + GET_PRICE_0(p->isMatch[state2][posStateNext]) +
4092 + LitEnc_GetPriceMatched(LIT_PROBS(position + lenTest, data[lenTest - 1]),
4093 + data[lenTest], data2[lenTest], p->ProbPrices);
4094 + state2 = kLiteralNextStates[state2];
4095 + posStateNext = (position + lenTest + 1) & p->pbMask;
4096 + nextRepMatchPrice = curAndLenCharPrice +
4097 + GET_PRICE_1(p->isMatch[state2][posStateNext]) +
4098 + GET_PRICE_1(p->isRep[state2]);
4100 + /* for (; lenTest2 >= 2; lenTest2--) */
4102 + UInt32 curAndLenPrice;
4104 + UInt32 offset = cur + lenTest + 1 + lenTest2;
4105 + while (lenEnd < offset)
4106 + p->opt[++lenEnd].price = kInfinityPrice;
4107 + curAndLenPrice = nextRepMatchPrice + GetRepPrice(p, 0, lenTest2, state2, posStateNext);
4108 + opt = &p->opt[offset];
4109 + if (curAndLenPrice < opt->price)
4111 + opt->price = curAndLenPrice;
4112 + opt->posPrev = cur + lenTest + 1;
4113 + opt->backPrev = 0;
4114 + opt->prev1IsChar = True;
4115 + opt->prev2 = True;
4116 + opt->posPrev2 = cur;
4117 + opt->backPrev2 = repIndex;
4124 + /* for (UInt32 lenTest = 2; lenTest <= newLen; lenTest++) */
4125 + if (newLen > numAvailableBytes)
4127 + newLen = numAvailableBytes;
4128 + for (numDistancePairs = 0; newLen > matchDistances[numDistancePairs]; numDistancePairs += 2);
4129 + matchDistances[numDistancePairs] = newLen;
4130 + numDistancePairs += 2;
4132 + if (newLen >= startLen)
4134 + UInt32 normalMatchPrice = matchPrice + GET_PRICE_0(p->isRep[state]);
4135 + UInt32 offs, curBack, posSlot;
4137 + while (lenEnd < cur + newLen)
4138 + p->opt[++lenEnd].price = kInfinityPrice;
4141 + while (startLen > matchDistances[offs])
4143 + curBack = matchDistances[offs + 1];
4144 + GetPosSlot2(curBack, posSlot);
4145 + for (lenTest = /*2*/ startLen; ; lenTest++)
4147 + UInt32 curAndLenPrice = normalMatchPrice + p->lenEnc.prices[posState][lenTest - LZMA_MATCH_LEN_MIN];
4148 + UInt32 lenToPosState = GetLenToPosState(lenTest);
4150 + if (curBack < kNumFullDistances)
4151 + curAndLenPrice += p->distancesPrices[lenToPosState][curBack];
4153 + curAndLenPrice += p->posSlotPrices[lenToPosState][posSlot] + p->alignPrices[curBack & kAlignMask];
4155 + opt = &p->opt[cur + lenTest];
4156 + if (curAndLenPrice < opt->price)
4158 + opt->price = curAndLenPrice;
4159 + opt->posPrev = cur;
4160 + opt->backPrev = curBack + LZMA_NUM_REPS;
4161 + opt->prev1IsChar = False;
4164 + if (/*_maxMode && */lenTest == matchDistances[offs])
4166 + /* Try Match + Literal + Rep0 */
4167 + const Byte *data2 = data - (curBack + 1);
4168 + UInt32 lenTest2 = lenTest + 1;
4169 + UInt32 limit = lenTest2 + p->numFastBytes;
4170 + UInt32 nextRepMatchPrice;
4171 + if (limit > numAvailableBytesFull)
4172 + limit = numAvailableBytesFull;
4173 + for (; lenTest2 < limit && data[lenTest2] == data2[lenTest2]; lenTest2++);
4174 + lenTest2 -= lenTest + 1;
4175 + if (lenTest2 >= 2)
4177 + UInt32 state2 = kMatchNextStates[state];
4178 + UInt32 posStateNext = (position + lenTest) & p->pbMask;
4179 + UInt32 curAndLenCharPrice = curAndLenPrice +
4180 + GET_PRICE_0(p->isMatch[state2][posStateNext]) +
4181 + LitEnc_GetPriceMatched(LIT_PROBS(position + lenTest, data[lenTest - 1]),
4182 + data[lenTest], data2[lenTest], p->ProbPrices);
4183 + state2 = kLiteralNextStates[state2];
4184 + posStateNext = (posStateNext + 1) & p->pbMask;
4185 + nextRepMatchPrice = curAndLenCharPrice +
4186 + GET_PRICE_1(p->isMatch[state2][posStateNext]) +
4187 + GET_PRICE_1(p->isRep[state2]);
4189 + /* for (; lenTest2 >= 2; lenTest2--) */
4191 + UInt32 offset = cur + lenTest + 1 + lenTest2;
4192 + UInt32 curAndLenPrice;
4194 + while (lenEnd < offset)
4195 + p->opt[++lenEnd].price = kInfinityPrice;
4196 + curAndLenPrice = nextRepMatchPrice + GetRepPrice(p, 0, lenTest2, state2, posStateNext);
4197 + opt = &p->opt[offset];
4198 + if (curAndLenPrice < opt->price)
4200 + opt->price = curAndLenPrice;
4201 + opt->posPrev = cur + lenTest + 1;
4202 + opt->backPrev = 0;
4203 + opt->prev1IsChar = True;
4204 + opt->prev2 = True;
4205 + opt->posPrev2 = cur;
4206 + opt->backPrev2 = curBack + LZMA_NUM_REPS;
4211 + if (offs == numDistancePairs)
4213 + curBack = matchDistances[offs + 1];
4214 + if (curBack >= kNumFullDistances)
4215 + GetPosSlot2(curBack, posSlot);
4222 +#define ChangePair(smallDist, bigDist) (((bigDist) >> 7) > (smallDist))
4224 +static UInt32 GetOptimumFast(CLzmaEnc *p, UInt32 *backRes)
4226 + UInt32 numAvailableBytes = p->matchFinder.GetNumAvailableBytes(p->matchFinderObj);
4227 + UInt32 lenMain, numDistancePairs;
4229 + UInt32 repLens[LZMA_NUM_REPS];
4230 + UInt32 repMaxIndex, i;
4231 + UInt32 *matchDistances;
4234 + if (!p->longestMatchWasFound)
4236 + lenMain = ReadMatchDistances(p, &numDistancePairs);
4240 + lenMain = p->longestMatchLength;
4241 + numDistancePairs = p->numDistancePairs;
4242 + p->longestMatchWasFound = False;
4245 + data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - 1;
4246 + if (numAvailableBytes > LZMA_MATCH_LEN_MAX)
4247 + numAvailableBytes = LZMA_MATCH_LEN_MAX;
4248 + if (numAvailableBytes < 2)
4250 + *backRes = (UInt32)(-1);
4256 + for (i = 0; i < LZMA_NUM_REPS; i++)
4258 + const Byte *data2 = data - (p->reps[i] + 1);
4260 + if (data[0] != data2[0] || data[1] != data2[1])
4265 + for (len = 2; len < numAvailableBytes && data[len] == data2[len]; len++);
4266 + if (len >= p->numFastBytes)
4269 + MovePos(p, len - 1);
4273 + if (len > repLens[repMaxIndex])
4276 + matchDistances = p->matchDistances;
4277 + if (lenMain >= p->numFastBytes)
4279 + *backRes = matchDistances[numDistancePairs - 1] + LZMA_NUM_REPS;
4280 + MovePos(p, lenMain - 1);
4284 + backMain = 0; /* for GCC */
4287 + backMain = matchDistances[numDistancePairs - 1];
4288 + while (numDistancePairs > 2 && lenMain == matchDistances[numDistancePairs - 4] + 1)
4290 + if (!ChangePair(matchDistances[numDistancePairs - 3], backMain))
4292 + numDistancePairs -= 2;
4293 + lenMain = matchDistances[numDistancePairs - 2];
4294 + backMain = matchDistances[numDistancePairs - 1];
4296 + if (lenMain == 2 && backMain >= 0x80)
4300 + if (repLens[repMaxIndex] >= 2)
4302 + if (repLens[repMaxIndex] + 1 >= lenMain ||
4303 + (repLens[repMaxIndex] + 2 >= lenMain && (backMain > (1 << 9))) ||
4304 + (repLens[repMaxIndex] + 3 >= lenMain && (backMain > (1 << 15))))
4307 + *backRes = repMaxIndex;
4308 + lenRes = repLens[repMaxIndex];
4309 + MovePos(p, lenRes - 1);
4314 + if (lenMain >= 2 && numAvailableBytes > 2)
4317 + numAvailableBytes = p->matchFinder.GetNumAvailableBytes(p->matchFinderObj);
4318 + p->longestMatchLength = ReadMatchDistances(p, &p->numDistancePairs);
4319 + if (p->longestMatchLength >= 2)
4321 + UInt32 newDistance = matchDistances[p->numDistancePairs - 1];
4322 + if ((p->longestMatchLength >= lenMain && newDistance < backMain) ||
4323 + (p->longestMatchLength == lenMain + 1 && !ChangePair(backMain, newDistance)) ||
4324 + (p->longestMatchLength > lenMain + 1) ||
4325 + (p->longestMatchLength + 1 >= lenMain && lenMain >= 3 && ChangePair(newDistance, backMain)))
4327 + p->longestMatchWasFound = True;
4328 + *backRes = (UInt32)(-1);
4332 + data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - 1;
4333 + for (i = 0; i < LZMA_NUM_REPS; i++)
4336 + const Byte *data2 = data - (p->reps[i] + 1);
4337 + if (data[1] != data2[1] || data[2] != data2[2])
4342 + for (len = 2; len < numAvailableBytes && data[len] == data2[len]; len++);
4343 + if (len + 1 >= lenMain)
4345 + p->longestMatchWasFound = True;
4346 + *backRes = (UInt32)(-1);
4350 + *backRes = backMain + LZMA_NUM_REPS;
4351 + MovePos(p, lenMain - 2);
4354 + *backRes = (UInt32)(-1);
4358 +static void WriteEndMarker(CLzmaEnc *p, UInt32 posState)
4361 + RangeEnc_EncodeBit(&p->rc, &p->isMatch[p->state][posState], 1);
4362 + RangeEnc_EncodeBit(&p->rc, &p->isRep[p->state], 0);
4363 + p->state = kMatchNextStates[p->state];
4364 + len = LZMA_MATCH_LEN_MIN;
4365 + LenEnc_Encode2(&p->lenEnc, &p->rc, len - LZMA_MATCH_LEN_MIN, posState, !p->fastMode, p->ProbPrices);
4366 + RcTree_Encode(&p->rc, p->posSlotEncoder[GetLenToPosState(len)], kNumPosSlotBits, (1 << kNumPosSlotBits) - 1);
4367 + RangeEnc_EncodeDirectBits(&p->rc, (((UInt32)1 << 30) - 1) >> kNumAlignBits, 30 - kNumAlignBits);
4368 + RcTree_ReverseEncode(&p->rc, p->posAlignEncoder, kNumAlignBits, kAlignMask);
4371 +static SRes CheckErrors(CLzmaEnc *p)
4373 + if (p->result != SZ_OK)
4375 + if (p->rc.res != SZ_OK)
4376 + p->result = SZ_ERROR_WRITE;
4377 + if (p->matchFinderBase.result != SZ_OK)
4378 + p->result = SZ_ERROR_READ;
4379 + if (p->result != SZ_OK)
4380 + p->finished = True;
4384 +static SRes Flush(CLzmaEnc *p, UInt32 nowPos)
4386 + /* ReleaseMFStream(); */
4387 + p->finished = True;
4388 + if (p->writeEndMark)
4389 + WriteEndMarker(p, nowPos & p->pbMask);
4390 + RangeEnc_FlushData(&p->rc);
4391 + RangeEnc_FlushStream(&p->rc);
4392 + return CheckErrors(p);
4395 +static void FillAlignPrices(CLzmaEnc *p)
4398 + for (i = 0; i < kAlignTableSize; i++)
4399 + p->alignPrices[i] = RcTree_ReverseGetPrice(p->posAlignEncoder, kNumAlignBits, i, p->ProbPrices);
4400 + p->alignPriceCount = 0;
4403 +static void FillDistancesPrices(CLzmaEnc *p)
4405 + UInt32 tempPrices[kNumFullDistances];
4406 + UInt32 i, lenToPosState;
4407 + for (i = kStartPosModelIndex; i < kNumFullDistances; i++)
4409 + UInt32 posSlot = GetPosSlot1(i);
4410 + UInt32 footerBits = ((posSlot >> 1) - 1);
4411 + UInt32 base = ((2 | (posSlot & 1)) << footerBits);
4412 + tempPrices[i] = RcTree_ReverseGetPrice(p->posEncoders + base - posSlot - 1, footerBits, i - base, p->ProbPrices);
4415 + for (lenToPosState = 0; lenToPosState < kNumLenToPosStates; lenToPosState++)
4418 + const CLzmaProb *encoder = p->posSlotEncoder[lenToPosState];
4419 + UInt32 *posSlotPrices = p->posSlotPrices[lenToPosState];
4420 + for (posSlot = 0; posSlot < p->distTableSize; posSlot++)
4421 + posSlotPrices[posSlot] = RcTree_GetPrice(encoder, kNumPosSlotBits, posSlot, p->ProbPrices);
4422 + for (posSlot = kEndPosModelIndex; posSlot < p->distTableSize; posSlot++)
4423 + posSlotPrices[posSlot] += ((((posSlot >> 1) - 1) - kNumAlignBits) << kNumBitPriceShiftBits);
4426 + UInt32 *distancesPrices = p->distancesPrices[lenToPosState];
4428 + for (i = 0; i < kStartPosModelIndex; i++)
4429 + distancesPrices[i] = posSlotPrices[i];
4430 + for (; i < kNumFullDistances; i++)
4431 + distancesPrices[i] = posSlotPrices[GetPosSlot1(i)] + tempPrices[i];
4434 + p->matchPriceCount = 0;
4437 +static void LzmaEnc_Construct(CLzmaEnc *p)
4439 + RangeEnc_Construct(&p->rc);
4440 + MatchFinder_Construct(&p->matchFinderBase);
4441 + #ifdef COMPRESS_MF_MT
4442 + MatchFinderMt_Construct(&p->matchFinderMt);
4443 + p->matchFinderMt.MatchFinder = &p->matchFinderBase;
4447 + CLzmaEncProps props;
4448 + LzmaEncProps_Init(&props);
4449 + LzmaEnc_SetProps(p, &props);
4452 + #ifndef LZMA_LOG_BSR
4453 + LzmaEnc_FastPosInit(p->g_FastPos);
4456 + LzmaEnc_InitPriceTables(p->ProbPrices);
4458 + p->saveState.litProbs = 0;
4461 +CLzmaEncHandle LzmaEnc_Create(ISzAlloc *alloc)
4464 + p = alloc->Alloc(alloc, sizeof(CLzmaEnc));
4466 + LzmaEnc_Construct((CLzmaEnc *)p);
4470 +static void LzmaEnc_FreeLits(CLzmaEnc *p, ISzAlloc *alloc)
4472 + alloc->Free(alloc, p->litProbs);
4473 + alloc->Free(alloc, p->saveState.litProbs);
4475 + p->saveState.litProbs = 0;
4478 +static void LzmaEnc_Destruct(CLzmaEnc *p, ISzAlloc *alloc, ISzAlloc *allocBig)
4480 + #ifdef COMPRESS_MF_MT
4481 + MatchFinderMt_Destruct(&p->matchFinderMt, allocBig);
4483 + MatchFinder_Free(&p->matchFinderBase, allocBig);
4484 + LzmaEnc_FreeLits(p, alloc);
4485 + RangeEnc_Free(&p->rc, alloc);
4488 +void LzmaEnc_Destroy(CLzmaEncHandle p, ISzAlloc *alloc, ISzAlloc *allocBig)
4490 + LzmaEnc_Destruct((CLzmaEnc *)p, alloc, allocBig);
4491 + alloc->Free(alloc, p);
4494 +static SRes LzmaEnc_CodeOneBlock(CLzmaEnc *p, Bool useLimits, UInt32 maxPackSize, UInt32 maxUnpackSize)
4496 + UInt32 nowPos32, startPos32;
4497 + if (p->inStream != 0)
4499 + p->matchFinderBase.stream = p->inStream;
4500 + p->matchFinder.Init(p->matchFinderObj);
4506 + RINOK(CheckErrors(p));
4508 + nowPos32 = (UInt32)p->nowPos64;
4509 + startPos32 = nowPos32;
4511 + if (p->nowPos64 == 0)
4513 + UInt32 numDistancePairs;
4515 + if (p->matchFinder.GetNumAvailableBytes(p->matchFinderObj) == 0)
4516 + return Flush(p, nowPos32);
4517 + ReadMatchDistances(p, &numDistancePairs);
4518 + RangeEnc_EncodeBit(&p->rc, &p->isMatch[p->state][0], 0);
4519 + p->state = kLiteralNextStates[p->state];
4520 + curByte = p->matchFinder.GetIndexByte(p->matchFinderObj, 0 - p->additionalOffset);
4521 + LitEnc_Encode(&p->rc, p->litProbs, curByte);
4522 + p->additionalOffset--;
4526 + if (p->matchFinder.GetNumAvailableBytes(p->matchFinderObj) != 0)
4529 + UInt32 pos, len, posState;
4532 + len = GetOptimumFast(p, &pos);
4534 + len = GetOptimum(p, nowPos32, &pos);
4537 + printf("\n pos = %4X, len = %d pos = %d", nowPos32, len, pos);
4540 + posState = nowPos32 & p->pbMask;
4541 + if (len == 1 && pos == 0xFFFFFFFF)
4547 + RangeEnc_EncodeBit(&p->rc, &p->isMatch[p->state][posState], 0);
4548 + data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - p->additionalOffset;
4550 + probs = LIT_PROBS(nowPos32, *(data - 1));
4551 + if (IsCharState(p->state))
4552 + LitEnc_Encode(&p->rc, probs, curByte);
4554 + LitEnc_EncodeMatched(&p->rc, probs, curByte, *(data - p->reps[0] - 1));
4555 + p->state = kLiteralNextStates[p->state];
4559 + RangeEnc_EncodeBit(&p->rc, &p->isMatch[p->state][posState], 1);
4560 + if (pos < LZMA_NUM_REPS)
4562 + RangeEnc_EncodeBit(&p->rc, &p->isRep[p->state], 1);
4565 + RangeEnc_EncodeBit(&p->rc, &p->isRepG0[p->state], 0);
4566 + RangeEnc_EncodeBit(&p->rc, &p->isRep0Long[p->state][posState], ((len == 1) ? 0 : 1));
4570 + UInt32 distance = p->reps[pos];
4571 + RangeEnc_EncodeBit(&p->rc, &p->isRepG0[p->state], 1);
4573 + RangeEnc_EncodeBit(&p->rc, &p->isRepG1[p->state], 0);
4576 + RangeEnc_EncodeBit(&p->rc, &p->isRepG1[p->state], 1);
4577 + RangeEnc_EncodeBit(&p->rc, &p->isRepG2[p->state], pos - 2);
4579 + p->reps[3] = p->reps[2];
4580 + p->reps[2] = p->reps[1];
4582 + p->reps[1] = p->reps[0];
4583 + p->reps[0] = distance;
4586 + p->state = kShortRepNextStates[p->state];
4589 + LenEnc_Encode2(&p->repLenEnc, &p->rc, len - LZMA_MATCH_LEN_MIN, posState, !p->fastMode, p->ProbPrices);
4590 + p->state = kRepNextStates[p->state];
4596 + RangeEnc_EncodeBit(&p->rc, &p->isRep[p->state], 0);
4597 + p->state = kMatchNextStates[p->state];
4598 + LenEnc_Encode2(&p->lenEnc, &p->rc, len - LZMA_MATCH_LEN_MIN, posState, !p->fastMode, p->ProbPrices);
4599 + pos -= LZMA_NUM_REPS;
4600 + GetPosSlot(pos, posSlot);
4601 + RcTree_Encode(&p->rc, p->posSlotEncoder[GetLenToPosState(len)], kNumPosSlotBits, posSlot);
4603 + if (posSlot >= kStartPosModelIndex)
4605 + UInt32 footerBits = ((posSlot >> 1) - 1);
4606 + UInt32 base = ((2 | (posSlot & 1)) << footerBits);
4607 + UInt32 posReduced = pos - base;
4609 + if (posSlot < kEndPosModelIndex)
4610 + RcTree_ReverseEncode(&p->rc, p->posEncoders + base - posSlot - 1, footerBits, posReduced);
4613 + RangeEnc_EncodeDirectBits(&p->rc, posReduced >> kNumAlignBits, footerBits - kNumAlignBits);
4614 + RcTree_ReverseEncode(&p->rc, p->posAlignEncoder, kNumAlignBits, posReduced & kAlignMask);
4615 + p->alignPriceCount++;
4618 + p->reps[3] = p->reps[2];
4619 + p->reps[2] = p->reps[1];
4620 + p->reps[1] = p->reps[0];
4622 + p->matchPriceCount++;
4625 + p->additionalOffset -= len;
4627 + if (p->additionalOffset == 0)
4632 + if (p->matchPriceCount >= (1 << 7))
4633 + FillDistancesPrices(p);
4634 + if (p->alignPriceCount >= kAlignTableSize)
4635 + FillAlignPrices(p);
4637 + if (p->matchFinder.GetNumAvailableBytes(p->matchFinderObj) == 0)
4639 + processed = nowPos32 - startPos32;
4642 + if (processed + kNumOpts + 300 >= maxUnpackSize ||
4643 + RangeEnc_GetProcessed(&p->rc) + kNumOpts * 2 >= maxPackSize)
4646 + else if (processed >= (1 << 15))
4648 + p->nowPos64 += nowPos32 - startPos32;
4649 + return CheckErrors(p);
4653 + p->nowPos64 += nowPos32 - startPos32;
4654 + return Flush(p, nowPos32);
4657 +#define kBigHashDicLimit ((UInt32)1 << 24)
4659 +static SRes LzmaEnc_Alloc(CLzmaEnc *p, UInt32 keepWindowSize, ISzAlloc *alloc, ISzAlloc *allocBig)
4661 + UInt32 beforeSize = kNumOpts;
4663 + if (!RangeEnc_Alloc(&p->rc, alloc))
4664 + return SZ_ERROR_MEM;
4665 + btMode = (p->matchFinderBase.btMode != 0);
4666 + #ifdef COMPRESS_MF_MT
4667 + p->mtMode = (p->multiThread && !p->fastMode && btMode);
4671 + unsigned lclp = p->lc + p->lp;
4672 + if (p->litProbs == 0 || p->saveState.litProbs == 0 || p->lclp != lclp)
4674 + LzmaEnc_FreeLits(p, alloc);
4675 + p->litProbs = (CLzmaProb *)alloc->Alloc(alloc, (0x300 << lclp) * sizeof(CLzmaProb));
4676 + p->saveState.litProbs = (CLzmaProb *)alloc->Alloc(alloc, (0x300 << lclp) * sizeof(CLzmaProb));
4677 + if (p->litProbs == 0 || p->saveState.litProbs == 0)
4679 + LzmaEnc_FreeLits(p, alloc);
4680 + return SZ_ERROR_MEM;
4686 + p->matchFinderBase.bigHash = (p->dictSize > kBigHashDicLimit);
4688 + if (beforeSize + p->dictSize < keepWindowSize)
4689 + beforeSize = keepWindowSize - p->dictSize;
4691 + #ifdef COMPRESS_MF_MT
4694 + RINOK(MatchFinderMt_Create(&p->matchFinderMt, p->dictSize, beforeSize, p->numFastBytes, LZMA_MATCH_LEN_MAX, allocBig));
4695 + p->matchFinderObj = &p->matchFinderMt;
4696 + MatchFinderMt_CreateVTable(&p->matchFinderMt, &p->matchFinder);
4701 + if (!MatchFinder_Create(&p->matchFinderBase, p->dictSize, beforeSize, p->numFastBytes, LZMA_MATCH_LEN_MAX, allocBig))
4702 + return SZ_ERROR_MEM;
4703 + p->matchFinderObj = &p->matchFinderBase;
4704 + MatchFinder_CreateVTable(&p->matchFinderBase, &p->matchFinder);
4709 +static void LzmaEnc_Init(CLzmaEnc *p)
4713 + for(i = 0 ; i < LZMA_NUM_REPS; i++)
4716 + RangeEnc_Init(&p->rc);
4719 + for (i = 0; i < kNumStates; i++)
4722 + for (j = 0; j < LZMA_NUM_PB_STATES_MAX; j++)
4724 + p->isMatch[i][j] = kProbInitValue;
4725 + p->isRep0Long[i][j] = kProbInitValue;
4727 + p->isRep[i] = kProbInitValue;
4728 + p->isRepG0[i] = kProbInitValue;
4729 + p->isRepG1[i] = kProbInitValue;
4730 + p->isRepG2[i] = kProbInitValue;
4734 + UInt32 num = 0x300 << (p->lp + p->lc);
4735 + for (i = 0; i < num; i++)
4736 + p->litProbs[i] = kProbInitValue;
4740 + for (i = 0; i < kNumLenToPosStates; i++)
4742 + CLzmaProb *probs = p->posSlotEncoder[i];
4744 + for (j = 0; j < (1 << kNumPosSlotBits); j++)
4745 + probs[j] = kProbInitValue;
4749 + for(i = 0; i < kNumFullDistances - kEndPosModelIndex; i++)
4750 + p->posEncoders[i] = kProbInitValue;
4753 + LenEnc_Init(&p->lenEnc.p);
4754 + LenEnc_Init(&p->repLenEnc.p);
4756 + for (i = 0; i < (1 << kNumAlignBits); i++)
4757 + p->posAlignEncoder[i] = kProbInitValue;
4759 + p->longestMatchWasFound = False;
4760 + p->optimumEndIndex = 0;
4761 + p->optimumCurrentIndex = 0;
4762 + p->additionalOffset = 0;
4764 + p->pbMask = (1 << p->pb) - 1;
4765 + p->lpMask = (1 << p->lp) - 1;
4768 +static void LzmaEnc_InitPrices(CLzmaEnc *p)
4772 + FillDistancesPrices(p);
4773 + FillAlignPrices(p);
4776 + p->lenEnc.tableSize =
4777 + p->repLenEnc.tableSize =
4778 + p->numFastBytes + 1 - LZMA_MATCH_LEN_MIN;
4779 + LenPriceEnc_UpdateTables(&p->lenEnc, 1 << p->pb, p->ProbPrices);
4780 + LenPriceEnc_UpdateTables(&p->repLenEnc, 1 << p->pb, p->ProbPrices);
4783 +static SRes LzmaEnc_AllocAndInit(CLzmaEnc *p, UInt32 keepWindowSize, ISzAlloc *alloc, ISzAlloc *allocBig)
4786 + for (i = 0; i < (UInt32)kDicLogSizeMaxCompress; i++)
4787 + if (p->dictSize <= ((UInt32)1 << i))
4789 + p->distTableSize = i * 2;
4791 + p->finished = False;
4792 + p->result = SZ_OK;
4793 + RINOK(LzmaEnc_Alloc(p, keepWindowSize, alloc, allocBig));
4795 + LzmaEnc_InitPrices(p);
4800 +static SRes LzmaEnc_Prepare(CLzmaEncHandle pp, ISeqInStream *inStream, ISeqOutStream *outStream,
4801 + ISzAlloc *alloc, ISzAlloc *allocBig)
4803 + CLzmaEnc *p = (CLzmaEnc *)pp;
4804 + p->inStream = inStream;
4805 + p->rc.outStream = outStream;
4806 + return LzmaEnc_AllocAndInit(p, 0, alloc, allocBig);
4809 +static SRes LzmaEnc_PrepareForLzma2(CLzmaEncHandle pp,
4810 + ISeqInStream *inStream, UInt32 keepWindowSize,
4811 + ISzAlloc *alloc, ISzAlloc *allocBig)
4813 + CLzmaEnc *p = (CLzmaEnc *)pp;
4814 + p->inStream = inStream;
4815 + return LzmaEnc_AllocAndInit(p, keepWindowSize, alloc, allocBig);
4818 +static void LzmaEnc_SetInputBuf(CLzmaEnc *p, const Byte *src, SizeT srcLen)
4820 + p->seqBufInStream.funcTable.Read = MyRead;
4821 + p->seqBufInStream.data = src;
4822 + p->seqBufInStream.rem = srcLen;
4825 +static SRes LzmaEnc_MemPrepare(CLzmaEncHandle pp, const Byte *src, SizeT srcLen,
4826 + UInt32 keepWindowSize, ISzAlloc *alloc, ISzAlloc *allocBig)
4828 + CLzmaEnc *p = (CLzmaEnc *)pp;
4829 + LzmaEnc_SetInputBuf(p, src, srcLen);
4830 + p->inStream = &p->seqBufInStream.funcTable;
4831 + return LzmaEnc_AllocAndInit(p, keepWindowSize, alloc, allocBig);
4834 +static void LzmaEnc_Finish(CLzmaEncHandle pp)
4836 + #ifdef COMPRESS_MF_MT
4837 + CLzmaEnc *p = (CLzmaEnc *)pp;
4839 + MatchFinderMt_ReleaseStream(&p->matchFinderMt);
4843 +typedef struct _CSeqOutStreamBuf
4845 + ISeqOutStream funcTable;
4849 +} CSeqOutStreamBuf;
4851 +static size_t MyWrite(void *pp, const void *data, size_t size)
4853 + CSeqOutStreamBuf *p = (CSeqOutStreamBuf *)pp;
4854 + if (p->rem < size)
4857 + p->overflow = True;
4859 + memcpy(p->data, data, size);
4866 +static UInt32 LzmaEnc_GetNumAvailableBytes(CLzmaEncHandle pp)
4868 + const CLzmaEnc *p = (CLzmaEnc *)pp;
4869 + return p->matchFinder.GetNumAvailableBytes(p->matchFinderObj);
4872 +static const Byte *LzmaEnc_GetCurBuf(CLzmaEncHandle pp)
4874 + const CLzmaEnc *p = (CLzmaEnc *)pp;
4875 + return p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - p->additionalOffset;
4878 +static SRes LzmaEnc_CodeOneMemBlock(CLzmaEncHandle pp, Bool reInit,
4879 + Byte *dest, size_t *destLen, UInt32 desiredPackSize, UInt32 *unpackSize)
4881 + CLzmaEnc *p = (CLzmaEnc *)pp;
4884 + CSeqOutStreamBuf outStream;
4886 + outStream.funcTable.Write = MyWrite;
4887 + outStream.data = dest;
4888 + outStream.rem = *destLen;
4889 + outStream.overflow = False;
4891 + p->writeEndMark = False;
4892 + p->finished = False;
4893 + p->result = SZ_OK;
4897 + LzmaEnc_InitPrices(p);
4898 + nowPos64 = p->nowPos64;
4899 + RangeEnc_Init(&p->rc);
4900 + p->rc.outStream = &outStream.funcTable;
4902 + res = LzmaEnc_CodeOneBlock(pp, True, desiredPackSize, *unpackSize);
4904 + *unpackSize = (UInt32)(p->nowPos64 - nowPos64);
4905 + *destLen -= outStream.rem;
4906 + if (outStream.overflow)
4907 + return SZ_ERROR_OUTPUT_EOF;
4912 +SRes LzmaEnc_Encode(CLzmaEncHandle pp, ISeqOutStream *outStream, ISeqInStream *inStream, ICompressProgress *progress,
4913 + ISzAlloc *alloc, ISzAlloc *allocBig)
4915 + CLzmaEnc *p = (CLzmaEnc *)pp;
4918 + #ifdef COMPRESS_MF_MT
4919 + Byte allocaDummy[0x300];
4921 + for (i = 0; i < 16; i++)
4922 + allocaDummy[i] = (Byte)i;
4925 + RINOK(LzmaEnc_Prepare(pp, inStream, outStream, alloc, allocBig));
4929 + res = LzmaEnc_CodeOneBlock(pp, False, 0, 0);
4930 + if (res != SZ_OK || p->finished != 0)
4932 + if (progress != 0)
4934 + res = progress->Progress(progress, p->nowPos64, RangeEnc_GetProcessed(&p->rc));
4937 + res = SZ_ERROR_PROGRESS;
4942 + LzmaEnc_Finish(pp);
4946 +SRes LzmaEnc_WriteProperties(CLzmaEncHandle pp, Byte *props, SizeT *size)
4948 + CLzmaEnc *p = (CLzmaEnc *)pp;
4950 + UInt32 dictSize = p->dictSize;
4951 + if (*size < LZMA_PROPS_SIZE)
4952 + return SZ_ERROR_PARAM;
4953 + *size = LZMA_PROPS_SIZE;
4954 + props[0] = (Byte)((p->pb * 5 + p->lp) * 9 + p->lc);
4956 + for (i = 11; i <= 30; i++)
4958 + if (dictSize <= ((UInt32)2 << i))
4960 + dictSize = (2 << i);
4963 + if (dictSize <= ((UInt32)3 << i))
4965 + dictSize = (3 << i);
4970 + for (i = 0; i < 4; i++)
4971 + props[1 + i] = (Byte)(dictSize >> (8 * i));
4975 +SRes LzmaEnc_MemEncode(CLzmaEncHandle pp, Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen,
4976 + int writeEndMark, ICompressProgress *progress, ISzAlloc *alloc, ISzAlloc *allocBig)
4979 + CLzmaEnc *p = (CLzmaEnc *)pp;
4981 + CSeqOutStreamBuf outStream;
4983 + LzmaEnc_SetInputBuf(p, src, srcLen);
4985 + outStream.funcTable.Write = MyWrite;
4986 + outStream.data = dest;
4987 + outStream.rem = *destLen;
4988 + outStream.overflow = False;
4990 + p->writeEndMark = writeEndMark;
4991 + res = LzmaEnc_Encode(pp, &outStream.funcTable, &p->seqBufInStream.funcTable,
4992 + progress, alloc, allocBig);
4994 + *destLen -= outStream.rem;
4995 + if (outStream.overflow)
4996 + return SZ_ERROR_OUTPUT_EOF;
5000 +SRes LzmaEncode(Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen,
5001 + const CLzmaEncProps *props, Byte *propsEncoded, SizeT *propsSize, int writeEndMark,
5002 + ICompressProgress *progress, ISzAlloc *alloc, ISzAlloc *allocBig)
5004 + CLzmaEnc *p = (CLzmaEnc *)LzmaEnc_Create(alloc);
5007 + return SZ_ERROR_MEM;
5009 + res = LzmaEnc_SetProps(p, props);
5012 + res = LzmaEnc_WriteProperties(p, propsEncoded, propsSize);
5014 + res = LzmaEnc_MemEncode(p, dest, destLen, src, srcLen,
5015 + writeEndMark, progress, alloc, allocBig);
5018 + LzmaEnc_Destroy(p, alloc, allocBig);
5021 --- a/jffsX-utils/mkfs.jffs2.c
5022 +++ b/jffsX-utils/mkfs.jffs2.c
5023 @@ -1668,11 +1668,11 @@ int main(int argc, char **argv)
5025 erase_block_size *= units;
5027 - /* If it's less than 8KiB, they're not allowed */
5028 - if (erase_block_size < 0x2000) {
5029 - fprintf(stderr, "Erase size 0x%x too small. Increasing to 8KiB minimum\n",
5030 + /* If it's less than 4KiB, they're not allowed */
5031 + if (erase_block_size < 0x1000) {
5032 + fprintf(stderr, "Erase size 0x%x too small. Increasing to 4KiB minimum\n",
5034 - erase_block_size = 0x2000;
5035 + erase_block_size = 0x1000;