1 --- a/jffsX-utils/Makemodule.am
2 +++ b/jffsX-utils/Makemodule.am
3 @@ -4,11 +4,19 @@ 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
16 +mkfs_jffs2_SOURCES += jffsX-utils/compr_lzo.c
19 mkfs_jffs2_LDADD = libmtd.a $(ZLIB_LIBS) $(LZO_LIBS)
20 -mkfs_jffs2_CPPFLAGS = $(AM_CPPFLAGS) $(ZLIB_CFLAGS) $(LZO_CFLAGS)
21 +mkfs_jffs2_CPPFLAGS = $(AM_CPPFLAGS) $(ZLIB_CFLAGS) $(LZO_CFLAGS) -I./include/linux/lzma
23 jffs2reader_SOURCES = jffsX-utils/jffs2reader.c
24 jffs2reader_LDADD = libmtd.a $(ZLIB_LIBS) $(LZO_LIBS)
25 --- a/jffsX-utils/compr.c
26 +++ b/jffsX-utils/compr.c
27 @@ -520,6 +520,9 @@ int jffs2_compressors_init(void)
28 #ifdef CONFIG_JFFS2_LZO
31 +#ifdef CONFIG_JFFS2_LZMA
37 @@ -534,5 +537,8 @@ int jffs2_compressors_exit(void)
38 #ifdef CONFIG_JFFS2_LZO
41 +#ifdef CONFIG_JFFS2_LZMA
46 --- a/jffsX-utils/compr.h
47 +++ b/jffsX-utils/compr.h
50 #define CONFIG_JFFS2_ZLIB
51 #define CONFIG_JFFS2_RTIME
52 -#define CONFIG_JFFS2_LZO
53 +#define CONFIG_JFFS2_LZMA
55 #define JFFS2_RUBINMIPS_PRIORITY 10
56 #define JFFS2_DYNRUBIN_PRIORITY 20
57 #define JFFS2_RTIME_PRIORITY 50
58 -#define JFFS2_ZLIB_PRIORITY 60
59 -#define JFFS2_LZO_PRIORITY 80
60 +#define JFFS2_LZMA_PRIORITY 70
61 +#define JFFS2_ZLIB_PRIORITY 80
62 +#define JFFS2_LZO_PRIORITY 90
64 #define JFFS2_COMPR_MODE_NONE 0
65 #define JFFS2_COMPR_MODE_PRIORITY 1
66 @@ -115,5 +116,10 @@ void jffs2_rtime_exit(void);
67 int jffs2_lzo_init(void);
68 void jffs2_lzo_exit(void);
70 +#ifdef CONFIG_JFFS2_LZMA
71 +int jffs2_lzma_init(void);
72 +void jffs2_lzma_exit(void);
76 #endif /* __JFFS2_COMPR_H__ */
78 +++ b/jffsX-utils/compr_lzma.c
81 + * JFFS2 -- Journalling Flash File System, Version 2.
83 + * For licensing information, see the file 'LICENCE' in this directory.
85 + * JFFS2 wrapper to the LZMA C SDK
89 +#include <linux/lzma.h>
93 + static DEFINE_MUTEX(deflate_mutex);
97 +Byte propsEncoded[LZMA_PROPS_SIZE];
98 +SizeT propsSize = sizeof(propsEncoded);
100 +STATIC void lzma_free_workspace(void)
102 + LzmaEnc_Destroy(p, &lzma_alloc, &lzma_alloc);
105 +STATIC int INIT lzma_alloc_workspace(CLzmaEncProps *props)
107 + if ((p = (CLzmaEncHandle *)LzmaEnc_Create(&lzma_alloc)) == NULL)
109 + PRINT_ERROR("Failed to allocate lzma deflate workspace\n");
113 + if (LzmaEnc_SetProps(p, props) != SZ_OK)
115 + lzma_free_workspace();
119 + if (LzmaEnc_WriteProperties(p, propsEncoded, &propsSize) != SZ_OK)
121 + lzma_free_workspace();
128 +STATIC int jffs2_lzma_compress(unsigned char *data_in, unsigned char *cpage_out,
129 + uint32_t *sourcelen, uint32_t *dstlen)
131 + SizeT compress_size = (SizeT)(*dstlen);
135 + mutex_lock(&deflate_mutex);
138 + ret = LzmaEnc_MemEncode(p, cpage_out, &compress_size, data_in, *sourcelen,
139 + 0, NULL, &lzma_alloc, &lzma_alloc);
142 + mutex_unlock(&deflate_mutex);
148 + *dstlen = (uint32_t)compress_size;
153 +STATIC int jffs2_lzma_decompress(unsigned char *data_in, unsigned char *cpage_out,
154 + uint32_t srclen, uint32_t destlen)
157 + SizeT dl = (SizeT)destlen;
158 + SizeT sl = (SizeT)srclen;
159 + ELzmaStatus status;
161 + ret = LzmaDecode(cpage_out, &dl, data_in, &sl, propsEncoded,
162 + propsSize, LZMA_FINISH_ANY, &status, &lzma_alloc);
164 + if (ret != SZ_OK || status == LZMA_STATUS_NOT_FINISHED || dl != (SizeT)destlen)
170 +static struct jffs2_compressor jffs2_lzma_comp = {
171 + .priority = JFFS2_LZMA_PRIORITY,
173 + .compr = JFFS2_COMPR_LZMA,
174 + .compress = &jffs2_lzma_compress,
175 + .decompress = &jffs2_lzma_decompress,
179 +int INIT jffs2_lzma_init(void)
182 + CLzmaEncProps props;
183 + LzmaEncProps_Init(&props);
185 + props.dictSize = LZMA_BEST_DICT(0x2000);
186 + props.level = LZMA_BEST_LEVEL;
187 + props.lc = LZMA_BEST_LC;
188 + props.lp = LZMA_BEST_LP;
189 + props.pb = LZMA_BEST_PB;
190 + props.fb = LZMA_BEST_FB;
192 + ret = lzma_alloc_workspace(&props);
196 + ret = jffs2_register_compressor(&jffs2_lzma_comp);
198 + lzma_free_workspace();
203 +void jffs2_lzma_exit(void)
205 + jffs2_unregister_compressor(&jffs2_lzma_comp);
206 + lzma_free_workspace();
208 --- a/include/linux/jffs2.h
209 +++ b/include/linux/jffs2.h
211 #define JFFS2_COMPR_DYNRUBIN 0x05
212 #define JFFS2_COMPR_ZLIB 0x06
213 #define JFFS2_COMPR_LZO 0x07
214 +#define JFFS2_COMPR_LZMA 0x08
215 /* Compatibility flags. */
216 #define JFFS2_COMPAT_MASK 0xc000 /* What do to if an unknown nodetype is found */
217 #define JFFS2_NODE_ACCURATE 0x2000
219 +++ b/include/linux/lzma.h
225 + #include <linux/kernel.h>
226 + #include <linux/sched.h>
227 + #include <linux/slab.h>
228 + #include <linux/vmalloc.h>
229 + #include <linux/init.h>
230 + #define LZMA_MALLOC vmalloc
231 + #define LZMA_FREE vfree
232 + #define PRINT_ERROR(msg) printk(KERN_WARNING #msg)
233 + #define INIT __init
234 + #define STATIC static
236 + #include <stdint.h>
237 + #include <stdlib.h>
239 + #include <unistd.h>
240 + #include <string.h>
242 + #include <linux/jffs2.h>
244 + extern int page_size;
245 + #define PAGE_SIZE page_size
247 + #define LZMA_MALLOC malloc
248 + #define LZMA_FREE free
249 + #define PRINT_ERROR(msg) fprintf(stderr, msg)
251 + #define STATIC static
254 +#include "lzma/LzmaDec.h"
255 +#include "lzma/LzmaEnc.h"
257 +#define LZMA_BEST_LEVEL (9)
258 +#define LZMA_BEST_LC (0)
259 +#define LZMA_BEST_LP (0)
260 +#define LZMA_BEST_PB (0)
261 +#define LZMA_BEST_FB (273)
263 +#define LZMA_BEST_DICT(n) (((int)((n) / 2)) * 2)
265 +static void *p_lzma_malloc(void *p, size_t size)
270 + return LZMA_MALLOC(size);
273 +static void p_lzma_free(void *p, void *address)
275 + if (address != NULL)
276 + LZMA_FREE(address);
279 +static ISzAlloc lzma_alloc = {p_lzma_malloc, p_lzma_free};
283 +++ b/include/linux/lzma/LzFind.h
285 +/* LzFind.h -- Match finder for LZ algorithms
287 +Copyright (c) 1999-2008 Igor Pavlov
288 +You can use any of the following license options:
289 + 1) GNU Lesser General Public License (GNU LGPL)
290 + 2) Common Public License (CPL)
291 + 3) Common Development and Distribution License (CDDL) Version 1.0
292 + 4) Igor Pavlov, as the author of this code, expressly permits you to
293 + statically or dynamically link your code (or bind by name) to this file,
294 + while you keep this file unmodified.
302 +typedef UInt32 CLzRef;
304 +typedef struct _CMatchFinder
312 + UInt32 cyclicBufferPos;
313 + UInt32 cyclicBufferSize; /* it must be = (historySize + 1) */
315 + UInt32 matchMaxLen;
322 + ISeqInStream *stream;
323 + int streamEndWasReached;
326 + UInt32 keepSizeBefore;
327 + UInt32 keepSizeAfter;
329 + UInt32 numHashBytes;
332 + /* int skipModeBits; */
334 + UInt32 historySize;
335 + UInt32 fixedHashSize;
336 + UInt32 hashSizeSum;
342 +#define Inline_MatchFinder_GetPointerToCurrentPos(p) ((p)->buffer)
343 +#define Inline_MatchFinder_GetIndexByte(p, index) ((p)->buffer[(Int32)(index)])
345 +#define Inline_MatchFinder_GetNumAvailableBytes(p) ((p)->streamPos - (p)->pos)
347 +int MatchFinder_NeedMove(CMatchFinder *p);
348 +Byte *MatchFinder_GetPointerToCurrentPos(CMatchFinder *p);
349 +void MatchFinder_MoveBlock(CMatchFinder *p);
350 +void MatchFinder_ReadIfRequired(CMatchFinder *p);
352 +void MatchFinder_Construct(CMatchFinder *p);
355 + historySize <= 3 GB
356 + keepAddBufferBefore + matchMaxLen + keepAddBufferAfter < 511MB
358 +int MatchFinder_Create(CMatchFinder *p, UInt32 historySize,
359 + UInt32 keepAddBufferBefore, UInt32 matchMaxLen, UInt32 keepAddBufferAfter,
361 +void MatchFinder_Free(CMatchFinder *p, ISzAlloc *alloc);
362 +void MatchFinder_Normalize3(UInt32 subValue, CLzRef *items, UInt32 numItems);
363 +void MatchFinder_ReduceOffsets(CMatchFinder *p, UInt32 subValue);
365 +UInt32 * GetMatchesSpec1(UInt32 lenLimit, UInt32 curMatch, UInt32 pos, const Byte *buffer, CLzRef *son,
366 + UInt32 _cyclicBufferPos, UInt32 _cyclicBufferSize, UInt32 _cutValue,
367 + UInt32 *distances, UInt32 maxLen);
371 + Mf_GetNumAvailableBytes_Func must be called before each Mf_GetMatchLen_Func.
372 + Mf_GetPointerToCurrentPos_Func's result must be used only before any other function
375 +typedef void (*Mf_Init_Func)(void *object);
376 +typedef Byte (*Mf_GetIndexByte_Func)(void *object, Int32 index);
377 +typedef UInt32 (*Mf_GetNumAvailableBytes_Func)(void *object);
378 +typedef const Byte * (*Mf_GetPointerToCurrentPos_Func)(void *object);
379 +typedef UInt32 (*Mf_GetMatches_Func)(void *object, UInt32 *distances);
380 +typedef void (*Mf_Skip_Func)(void *object, UInt32);
382 +typedef struct _IMatchFinder
385 + Mf_GetIndexByte_Func GetIndexByte;
386 + Mf_GetNumAvailableBytes_Func GetNumAvailableBytes;
387 + Mf_GetPointerToCurrentPos_Func GetPointerToCurrentPos;
388 + Mf_GetMatches_Func GetMatches;
392 +void MatchFinder_CreateVTable(CMatchFinder *p, IMatchFinder *vTable);
394 +void MatchFinder_Init(CMatchFinder *p);
395 +UInt32 Bt3Zip_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances);
396 +UInt32 Hc3Zip_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances);
397 +void Bt3Zip_MatchFinder_Skip(CMatchFinder *p, UInt32 num);
398 +void Hc3Zip_MatchFinder_Skip(CMatchFinder *p, UInt32 num);
402 +++ b/include/linux/lzma/LzHash.h
404 +/* LzHash.h -- HASH functions for LZ algorithms
406 +Copyright (c) 1999-2008 Igor Pavlov
407 +Read LzFind.h for license options */
412 +#define kHash2Size (1 << 10)
413 +#define kHash3Size (1 << 16)
414 +#define kHash4Size (1 << 20)
416 +#define kFix3HashSize (kHash2Size)
417 +#define kFix4HashSize (kHash2Size + kHash3Size)
418 +#define kFix5HashSize (kHash2Size + kHash3Size + kHash4Size)
420 +#define HASH2_CALC hashValue = cur[0] | ((UInt32)cur[1] << 8);
422 +#define HASH3_CALC { \
423 + UInt32 temp = p->crc[cur[0]] ^ cur[1]; \
424 + hash2Value = temp & (kHash2Size - 1); \
425 + hashValue = (temp ^ ((UInt32)cur[2] << 8)) & p->hashMask; }
427 +#define HASH4_CALC { \
428 + UInt32 temp = p->crc[cur[0]] ^ cur[1]; \
429 + hash2Value = temp & (kHash2Size - 1); \
430 + hash3Value = (temp ^ ((UInt32)cur[2] << 8)) & (kHash3Size - 1); \
431 + hashValue = (temp ^ ((UInt32)cur[2] << 8) ^ (p->crc[cur[3]] << 5)) & p->hashMask; }
433 +#define HASH5_CALC { \
434 + UInt32 temp = p->crc[cur[0]] ^ cur[1]; \
435 + hash2Value = temp & (kHash2Size - 1); \
436 + hash3Value = (temp ^ ((UInt32)cur[2] << 8)) & (kHash3Size - 1); \
437 + hash4Value = (temp ^ ((UInt32)cur[2] << 8) ^ (p->crc[cur[3]] << 5)); \
438 + hashValue = (hash4Value ^ (p->crc[cur[4]] << 3)) & p->hashMask; \
439 + hash4Value &= (kHash4Size - 1); }
441 +/* #define HASH_ZIP_CALC hashValue = ((cur[0] | ((UInt32)cur[1] << 8)) ^ p->crc[cur[2]]) & 0xFFFF; */
442 +#define HASH_ZIP_CALC hashValue = ((cur[2] | ((UInt32)cur[0] << 8)) ^ p->crc[cur[1]]) & 0xFFFF;
445 +#define MT_HASH2_CALC \
446 + hash2Value = (p->crc[cur[0]] ^ cur[1]) & (kHash2Size - 1);
448 +#define MT_HASH3_CALC { \
449 + UInt32 temp = p->crc[cur[0]] ^ cur[1]; \
450 + hash2Value = temp & (kHash2Size - 1); \
451 + hash3Value = (temp ^ ((UInt32)cur[2] << 8)) & (kHash3Size - 1); }
453 +#define MT_HASH4_CALC { \
454 + UInt32 temp = p->crc[cur[0]] ^ cur[1]; \
455 + hash2Value = temp & (kHash2Size - 1); \
456 + hash3Value = (temp ^ ((UInt32)cur[2] << 8)) & (kHash3Size - 1); \
457 + hash4Value = (temp ^ ((UInt32)cur[2] << 8) ^ (p->crc[cur[3]] << 5)) & (kHash4Size - 1); }
461 +++ b/include/linux/lzma/LzmaDec.h
463 +/* LzmaDec.h -- LZMA Decoder
465 +Copyright (c) 1999-2008 Igor Pavlov
466 +You can use any of the following license options:
467 + 1) GNU Lesser General Public License (GNU LGPL)
468 + 2) Common Public License (CPL)
469 + 3) Common Development and Distribution License (CDDL) Version 1.0
470 + 4) Igor Pavlov, as the author of this code, expressly permits you to
471 + statically or dynamically link your code (or bind by name) to this file,
472 + while you keep this file unmodified.
480 +/* #define _LZMA_PROB32 */
481 +/* _LZMA_PROB32 can increase the speed on some CPUs,
482 + but memory usage for CLzmaDec::probs will be doubled in that case */
485 +#define CLzmaProb UInt32
487 +#define CLzmaProb UInt16
491 +/* ---------- LZMA Properties ---------- */
493 +#define LZMA_PROPS_SIZE 5
495 +typedef struct _CLzmaProps
497 + unsigned lc, lp, pb;
501 +/* LzmaProps_Decode - decodes properties
504 + SZ_ERROR_UNSUPPORTED - Unsupported properties
507 +SRes LzmaProps_Decode(CLzmaProps *p, const Byte *data, unsigned size);
510 +/* ---------- LZMA Decoder state ---------- */
512 +/* LZMA_REQUIRED_INPUT_MAX = number of required input bytes for worst case.
513 + Num bits = log2((2^11 / 31) ^ 22) + 26 < 134 + 26 = 160; */
515 +#define LZMA_REQUIRED_INPUT_MAX 20
523 + UInt32 range, code;
526 + UInt32 processedPos;
527 + UInt32 checkDicSize;
530 + unsigned remainLen;
534 + unsigned tempBufSize;
535 + Byte tempBuf[LZMA_REQUIRED_INPUT_MAX];
538 +#define LzmaDec_Construct(p) { (p)->dic = 0; (p)->probs = 0; }
540 +void LzmaDec_Init(CLzmaDec *p);
542 +/* There are two types of LZMA streams:
543 + 0) Stream with end mark. That end mark adds about 6 bytes to compressed size.
544 + 1) Stream without end mark. You must know exact uncompressed size to decompress such stream. */
548 + LZMA_FINISH_ANY, /* finish at any point */
549 + LZMA_FINISH_END /* block must be finished at the end */
552 +/* ELzmaFinishMode has meaning only if the decoding reaches output limit !!!
554 + You must use LZMA_FINISH_END, when you know that current output buffer
555 + covers last bytes of block. In other cases you must use LZMA_FINISH_ANY.
557 + If LZMA decoder sees end marker before reaching output limit, it returns SZ_OK,
558 + and output value of destLen will be less than output buffer size limit.
559 + You can check status result also.
561 + You can use multiple checks to test data integrity after full decompression:
562 + 1) Check Result and "status" variable.
563 + 2) Check that output(destLen) = uncompressedSize, if you know real uncompressedSize.
564 + 3) Check that output(srcLen) = compressedSize, if you know real compressedSize.
565 + You must use correct finish mode in that case. */
569 + LZMA_STATUS_NOT_SPECIFIED, /* use main error code instead */
570 + LZMA_STATUS_FINISHED_WITH_MARK, /* stream was finished with end mark. */
571 + LZMA_STATUS_NOT_FINISHED, /* stream was not finished */
572 + LZMA_STATUS_NEEDS_MORE_INPUT, /* you must provide more input bytes */
573 + LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK /* there is probability that stream was finished without end mark */
576 +/* ELzmaStatus is used only as output value for function call */
579 +/* ---------- Interfaces ---------- */
581 +/* There are 3 levels of interfaces:
582 + 1) Dictionary Interface
583 + 2) Buffer Interface
584 + 3) One Call Interface
585 + You can select any of these interfaces, but don't mix functions from different
586 + groups for same object. */
589 +/* There are two variants to allocate state for Dictionary Interface:
590 + 1) LzmaDec_Allocate / LzmaDec_Free
591 + 2) LzmaDec_AllocateProbs / LzmaDec_FreeProbs
592 + You can use variant 2, if you set dictionary buffer manually.
593 + For Buffer Interface you must always use variant 1.
595 +LzmaDec_Allocate* can return:
597 + SZ_ERROR_MEM - Memory allocation error
598 + SZ_ERROR_UNSUPPORTED - Unsupported properties
601 +SRes LzmaDec_AllocateProbs(CLzmaDec *p, const Byte *props, unsigned propsSize, ISzAlloc *alloc);
602 +void LzmaDec_FreeProbs(CLzmaDec *p, ISzAlloc *alloc);
604 +SRes LzmaDec_Allocate(CLzmaDec *state, const Byte *prop, unsigned propsSize, ISzAlloc *alloc);
605 +void LzmaDec_Free(CLzmaDec *state, ISzAlloc *alloc);
607 +/* ---------- Dictionary Interface ---------- */
609 +/* You can use it, if you want to eliminate the overhead for data copying from
610 + dictionary to some other external buffer.
611 + You must work with CLzmaDec variables directly in this interface.
616 + for (each new stream)
619 + while (it needs more decompression)
621 + LzmaDec_DecodeToDic()
622 + use data from CLzmaDec::dic and update CLzmaDec::dicPos
628 +/* LzmaDec_DecodeToDic
630 + The decoding to internal dictionary buffer (CLzmaDec::dic).
631 + You must manually update CLzmaDec::dicPos, if it reaches CLzmaDec::dicBufSize !!!
634 + It has meaning only if the decoding reaches output limit (dicLimit).
635 + LZMA_FINISH_ANY - Decode just dicLimit bytes.
636 + LZMA_FINISH_END - Stream must be finished after dicLimit.
641 + LZMA_STATUS_FINISHED_WITH_MARK
642 + LZMA_STATUS_NOT_FINISHED
643 + LZMA_STATUS_NEEDS_MORE_INPUT
644 + LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK
645 + SZ_ERROR_DATA - Data error
648 +SRes LzmaDec_DecodeToDic(CLzmaDec *p, SizeT dicLimit,
649 + const Byte *src, SizeT *srcLen, ELzmaFinishMode finishMode, ELzmaStatus *status);
652 +/* ---------- Buffer Interface ---------- */
654 +/* It's zlib-like interface.
655 + See LzmaDec_DecodeToDic description for information about STEPS and return results,
656 + but you must use LzmaDec_DecodeToBuf instead of LzmaDec_DecodeToDic and you don't need
657 + to work with CLzmaDec variables manually.
660 + It has meaning only if the decoding reaches output limit (*destLen).
661 + LZMA_FINISH_ANY - Decode just destLen bytes.
662 + LZMA_FINISH_END - Stream must be finished after (*destLen).
665 +SRes LzmaDec_DecodeToBuf(CLzmaDec *p, Byte *dest, SizeT *destLen,
666 + const Byte *src, SizeT *srcLen, ELzmaFinishMode finishMode, ELzmaStatus *status);
669 +/* ---------- One Call Interface ---------- */
674 + It has meaning only if the decoding reaches output limit (*destLen).
675 + LZMA_FINISH_ANY - Decode just destLen bytes.
676 + LZMA_FINISH_END - Stream must be finished after (*destLen).
681 + LZMA_STATUS_FINISHED_WITH_MARK
682 + LZMA_STATUS_NOT_FINISHED
683 + LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK
684 + SZ_ERROR_DATA - Data error
685 + SZ_ERROR_MEM - Memory allocation error
686 + SZ_ERROR_UNSUPPORTED - Unsupported properties
687 + SZ_ERROR_INPUT_EOF - It needs more bytes in input buffer (src).
690 +SRes LzmaDecode(Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen,
691 + const Byte *propData, unsigned propSize, ELzmaFinishMode finishMode,
692 + ELzmaStatus *status, ISzAlloc *alloc);
696 +++ b/include/linux/lzma/LzmaEnc.h
698 +/* LzmaEnc.h -- LZMA Encoder
700 +Copyright (c) 1999-2008 Igor Pavlov
701 +Read LzFind.h for license options */
708 +#define LZMA_PROPS_SIZE 5
710 +typedef struct _CLzmaEncProps
712 + int level; /* 0 <= level <= 9 */
713 + UInt32 dictSize; /* (1 << 12) <= dictSize <= (1 << 27) for 32-bit version
714 + (1 << 12) <= dictSize <= (1 << 30) for 64-bit version
715 + default = (1 << 24) */
716 + int lc; /* 0 <= lc <= 8, default = 3 */
717 + int lp; /* 0 <= lp <= 4, default = 0 */
718 + int pb; /* 0 <= pb <= 4, default = 2 */
719 + int algo; /* 0 - fast, 1 - normal, default = 1 */
720 + int fb; /* 5 <= fb <= 273, default = 32 */
721 + int btMode; /* 0 - hashChain Mode, 1 - binTree mode - normal, default = 1 */
722 + int numHashBytes; /* 2, 3 or 4, default = 4 */
723 + UInt32 mc; /* 1 <= mc <= (1 << 30), default = 32 */
724 + unsigned writeEndMark; /* 0 - do not write EOPM, 1 - write EOPM, default = 0 */
725 + int numThreads; /* 1 or 2, default = 2 */
728 +void LzmaEncProps_Init(CLzmaEncProps *p);
729 +void LzmaEncProps_Normalize(CLzmaEncProps *p);
730 +UInt32 LzmaEncProps_GetDictSize(const CLzmaEncProps *props2);
733 +/* ---------- CLzmaEncHandle Interface ---------- */
735 +/* LzmaEnc_* functions can return the following exit codes:
738 + SZ_ERROR_MEM - Memory allocation error
739 + SZ_ERROR_PARAM - Incorrect paramater in props
740 + SZ_ERROR_WRITE - Write callback error.
741 + SZ_ERROR_PROGRESS - some break from progress callback
742 + SZ_ERROR_THREAD - errors in multithreading functions (only for Mt version)
745 +typedef void * CLzmaEncHandle;
747 +CLzmaEncHandle LzmaEnc_Create(ISzAlloc *alloc);
748 +void LzmaEnc_Destroy(CLzmaEncHandle p, ISzAlloc *alloc, ISzAlloc *allocBig);
749 +SRes LzmaEnc_SetProps(CLzmaEncHandle p, const CLzmaEncProps *props);
750 +SRes LzmaEnc_WriteProperties(CLzmaEncHandle p, Byte *properties, SizeT *size);
751 +SRes LzmaEnc_Encode(CLzmaEncHandle p, ISeqOutStream *outStream, ISeqInStream *inStream,
752 + ICompressProgress *progress, ISzAlloc *alloc, ISzAlloc *allocBig);
753 +SRes LzmaEnc_MemEncode(CLzmaEncHandle p, Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen,
754 + int writeEndMark, ICompressProgress *progress, ISzAlloc *alloc, ISzAlloc *allocBig);
756 +/* ---------- One Call Interface ---------- */
761 + SZ_ERROR_MEM - Memory allocation error
762 + SZ_ERROR_PARAM - Incorrect paramater
763 + SZ_ERROR_OUTPUT_EOF - output buffer overflow
764 + SZ_ERROR_THREAD - errors in multithreading functions (only for Mt version)
767 +SRes LzmaEncode(Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen,
768 + const CLzmaEncProps *props, Byte *propsEncoded, SizeT *propsSize, int writeEndMark,
769 + ICompressProgress *progress, ISzAlloc *alloc, ISzAlloc *allocBig);
773 +++ b/include/linux/lzma/Types.h
775 +/* Types.h -- Basic types
780 +#ifndef __7Z_TYPES_H
781 +#define __7Z_TYPES_H
785 +#define SZ_ERROR_DATA 1
786 +#define SZ_ERROR_MEM 2
787 +#define SZ_ERROR_CRC 3
788 +#define SZ_ERROR_UNSUPPORTED 4
789 +#define SZ_ERROR_PARAM 5
790 +#define SZ_ERROR_INPUT_EOF 6
791 +#define SZ_ERROR_OUTPUT_EOF 7
792 +#define SZ_ERROR_READ 8
793 +#define SZ_ERROR_WRITE 9
794 +#define SZ_ERROR_PROGRESS 10
795 +#define SZ_ERROR_FAIL 11
796 +#define SZ_ERROR_THREAD 12
798 +#define SZ_ERROR_ARCHIVE 16
799 +#define SZ_ERROR_NO_ARCHIVE 17
804 +#define RINOK(x) { int __result__ = (x); if (__result__ != 0) return __result__; }
807 +typedef unsigned char Byte;
808 +typedef short Int16;
809 +typedef unsigned short UInt16;
811 +#ifdef _LZMA_UINT32_IS_ULONG
813 +typedef unsigned long UInt32;
816 +typedef unsigned int UInt32;
819 +/* #define _SZ_NO_INT_64 */
820 +/* define it if your compiler doesn't support 64-bit integers */
822 +#ifdef _SZ_NO_INT_64
825 +typedef unsigned long UInt64;
829 +#if defined(_MSC_VER) || defined(__BORLANDC__)
830 +typedef __int64 Int64;
831 +typedef unsigned __int64 UInt64;
833 +typedef long long int Int64;
834 +typedef unsigned long long int UInt64;
839 +#ifdef _LZMA_NO_SYSTEM_SIZE_T
840 +typedef UInt32 SizeT;
843 +typedef size_t SizeT;
853 +#if _MSC_VER >= 1300
854 +#define MY_NO_INLINE __declspec(noinline)
856 +#define MY_NO_INLINE
859 +#define MY_CDECL __cdecl
860 +#define MY_STD_CALL __stdcall
861 +#define MY_FAST_CALL MY_NO_INLINE __fastcall
867 +#define MY_FAST_CALL
872 +/* The following interfaces use first parameter as pointer to structure */
876 + SRes (*Read)(void *p, void *buf, size_t *size);
877 + /* if (input(*size) != 0 && output(*size) == 0) means end_of_stream.
878 + (output(*size) < input(*size)) is allowed */
883 + size_t (*Write)(void *p, const void *buf, size_t size);
884 + /* Returns: result - the number of actually written bytes.
885 + (result < size) means error */
890 + SRes (*Progress)(void *p, UInt64 inSize, UInt64 outSize);
891 + /* Returns: result. (result != SZ_OK) means break.
892 + Value (UInt64)(Int64)-1 for size means unknown value. */
893 +} ICompressProgress;
897 + void *(*Alloc)(void *p, size_t size);
898 + void (*Free)(void *p, void *address); /* address can be 0 */
901 +#define IAlloc_Alloc(p, size) (p)->Alloc((p), size)
902 +#define IAlloc_Free(p, a) (p)->Free((p), a)
906 +++ b/jffsX-utils/lzma/LzFind.c
908 +/* LzFind.c -- Match finder for LZ algorithms
910 +Copyright (c) 1999-2008 Igor Pavlov
911 +Read LzFind.h for license options */
918 +#define kEmptyHashValue 0
919 +#define kMaxValForNormalize ((UInt32)0xFFFFFFFF)
920 +#define kNormalizeStepMin (1 << 10) /* it must be power of 2 */
921 +#define kNormalizeMask (~(kNormalizeStepMin - 1))
922 +#define kMaxHistorySize ((UInt32)3 << 30)
924 +#define kStartMaxLen 3
926 +static void LzInWindow_Free(CMatchFinder *p, ISzAlloc *alloc)
928 + if (!p->directInput)
930 + alloc->Free(alloc, p->bufferBase);
935 +/* keepSizeBefore + keepSizeAfter + keepSizeReserv must be < 4G) */
937 +static int LzInWindow_Create(CMatchFinder *p, UInt32 keepSizeReserv, ISzAlloc *alloc)
939 + UInt32 blockSize = p->keepSizeBefore + p->keepSizeAfter + keepSizeReserv;
940 + if (p->directInput)
942 + p->blockSize = blockSize;
945 + if (p->bufferBase == 0 || p->blockSize != blockSize)
947 + LzInWindow_Free(p, alloc);
948 + p->blockSize = blockSize;
949 + p->bufferBase = (Byte *)alloc->Alloc(alloc, (size_t)blockSize);
951 + return (p->bufferBase != 0);
954 +Byte *MatchFinder_GetPointerToCurrentPos(CMatchFinder *p) { return p->buffer; }
955 +static Byte MatchFinder_GetIndexByte(CMatchFinder *p, Int32 index) { return p->buffer[index]; }
957 +static UInt32 MatchFinder_GetNumAvailableBytes(CMatchFinder *p) { return p->streamPos - p->pos; }
959 +void MatchFinder_ReduceOffsets(CMatchFinder *p, UInt32 subValue)
961 + p->posLimit -= subValue;
962 + p->pos -= subValue;
963 + p->streamPos -= subValue;
966 +static void MatchFinder_ReadBlock(CMatchFinder *p)
968 + if (p->streamEndWasReached || p->result != SZ_OK)
972 + Byte *dest = p->buffer + (p->streamPos - p->pos);
973 + size_t size = (p->bufferBase + p->blockSize - dest);
976 + p->result = p->stream->Read(p->stream, dest, &size);
977 + if (p->result != SZ_OK)
981 + p->streamEndWasReached = 1;
984 + p->streamPos += (UInt32)size;
985 + if (p->streamPos - p->pos > p->keepSizeAfter)
990 +void MatchFinder_MoveBlock(CMatchFinder *p)
992 + memmove(p->bufferBase,
993 + p->buffer - p->keepSizeBefore,
994 + (size_t)(p->streamPos - p->pos + p->keepSizeBefore));
995 + p->buffer = p->bufferBase + p->keepSizeBefore;
998 +int MatchFinder_NeedMove(CMatchFinder *p)
1000 + /* if (p->streamEndWasReached) return 0; */
1001 + return ((size_t)(p->bufferBase + p->blockSize - p->buffer) <= p->keepSizeAfter);
1004 +void MatchFinder_ReadIfRequired(CMatchFinder *p)
1006 + if (p->streamEndWasReached)
1008 + if (p->keepSizeAfter >= p->streamPos - p->pos)
1009 + MatchFinder_ReadBlock(p);
1012 +static void MatchFinder_CheckAndMoveAndRead(CMatchFinder *p)
1014 + if (MatchFinder_NeedMove(p))
1015 + MatchFinder_MoveBlock(p);
1016 + MatchFinder_ReadBlock(p);
1019 +static void MatchFinder_SetDefaultSettings(CMatchFinder *p)
1023 + p->numHashBytes = 4;
1024 + /* p->skipModeBits = 0; */
1025 + p->directInput = 0;
1029 +#define kCrcPoly 0xEDB88320
1031 +void MatchFinder_Construct(CMatchFinder *p)
1034 + p->bufferBase = 0;
1035 + p->directInput = 0;
1037 + MatchFinder_SetDefaultSettings(p);
1039 + for (i = 0; i < 256; i++)
1043 + for (j = 0; j < 8; j++)
1044 + r = (r >> 1) ^ (kCrcPoly & ~((r & 1) - 1));
1049 +static void MatchFinder_FreeThisClassMemory(CMatchFinder *p, ISzAlloc *alloc)
1051 + alloc->Free(alloc, p->hash);
1055 +void MatchFinder_Free(CMatchFinder *p, ISzAlloc *alloc)
1057 + MatchFinder_FreeThisClassMemory(p, alloc);
1058 + LzInWindow_Free(p, alloc);
1061 +static CLzRef* AllocRefs(UInt32 num, ISzAlloc *alloc)
1063 + size_t sizeInBytes = (size_t)num * sizeof(CLzRef);
1064 + if (sizeInBytes / sizeof(CLzRef) != num)
1066 + return (CLzRef *)alloc->Alloc(alloc, sizeInBytes);
1069 +int MatchFinder_Create(CMatchFinder *p, UInt32 historySize,
1070 + UInt32 keepAddBufferBefore, UInt32 matchMaxLen, UInt32 keepAddBufferAfter,
1073 + UInt32 sizeReserv;
1074 + if (historySize > kMaxHistorySize)
1076 + MatchFinder_Free(p, alloc);
1079 + sizeReserv = historySize >> 1;
1080 + if (historySize > ((UInt32)2 << 30))
1081 + sizeReserv = historySize >> 2;
1082 + sizeReserv += (keepAddBufferBefore + matchMaxLen + keepAddBufferAfter) / 2 + (1 << 19);
1084 + p->keepSizeBefore = historySize + keepAddBufferBefore + 1;
1085 + p->keepSizeAfter = matchMaxLen + keepAddBufferAfter;
1086 + /* we need one additional byte, since we use MoveBlock after pos++ and before dictionary using */
1087 + if (LzInWindow_Create(p, sizeReserv, alloc))
1089 + UInt32 newCyclicBufferSize = (historySize /* >> p->skipModeBits */) + 1;
1091 + p->matchMaxLen = matchMaxLen;
1093 + p->fixedHashSize = 0;
1094 + if (p->numHashBytes == 2)
1095 + hs = (1 << 16) - 1;
1098 + hs = historySize - 1;
1104 + /* hs >>= p->skipModeBits; */
1105 + hs |= 0xFFFF; /* don't change it! It's required for Deflate */
1106 + if (hs > (1 << 24))
1108 + if (p->numHashBytes == 3)
1109 + hs = (1 << 24) - 1;
1116 + if (p->numHashBytes > 2) p->fixedHashSize += kHash2Size;
1117 + if (p->numHashBytes > 3) p->fixedHashSize += kHash3Size;
1118 + if (p->numHashBytes > 4) p->fixedHashSize += kHash4Size;
1119 + hs += p->fixedHashSize;
1123 + UInt32 prevSize = p->hashSizeSum + p->numSons;
1125 + p->historySize = historySize;
1126 + p->hashSizeSum = hs;
1127 + p->cyclicBufferSize = newCyclicBufferSize;
1128 + p->numSons = (p->btMode ? newCyclicBufferSize * 2 : newCyclicBufferSize);
1129 + newSize = p->hashSizeSum + p->numSons;
1130 + if (p->hash != 0 && prevSize == newSize)
1132 + MatchFinder_FreeThisClassMemory(p, alloc);
1133 + p->hash = AllocRefs(newSize, alloc);
1136 + p->son = p->hash + p->hashSizeSum;
1141 + MatchFinder_Free(p, alloc);
1145 +static void MatchFinder_SetLimits(CMatchFinder *p)
1147 + UInt32 limit = kMaxValForNormalize - p->pos;
1148 + UInt32 limit2 = p->cyclicBufferSize - p->cyclicBufferPos;
1149 + if (limit2 < limit)
1151 + limit2 = p->streamPos - p->pos;
1152 + if (limit2 <= p->keepSizeAfter)
1158 + limit2 -= p->keepSizeAfter;
1159 + if (limit2 < limit)
1162 + UInt32 lenLimit = p->streamPos - p->pos;
1163 + if (lenLimit > p->matchMaxLen)
1164 + lenLimit = p->matchMaxLen;
1165 + p->lenLimit = lenLimit;
1167 + p->posLimit = p->pos + limit;
1170 +void MatchFinder_Init(CMatchFinder *p)
1173 + for(i = 0; i < p->hashSizeSum; i++)
1174 + p->hash[i] = kEmptyHashValue;
1175 + p->cyclicBufferPos = 0;
1176 + p->buffer = p->bufferBase;
1177 + p->pos = p->streamPos = p->cyclicBufferSize;
1178 + p->result = SZ_OK;
1179 + p->streamEndWasReached = 0;
1180 + MatchFinder_ReadBlock(p);
1181 + MatchFinder_SetLimits(p);
1184 +static UInt32 MatchFinder_GetSubValue(CMatchFinder *p)
1186 + return (p->pos - p->historySize - 1) & kNormalizeMask;
1189 +void MatchFinder_Normalize3(UInt32 subValue, CLzRef *items, UInt32 numItems)
1192 + for (i = 0; i < numItems; i++)
1194 + UInt32 value = items[i];
1195 + if (value <= subValue)
1196 + value = kEmptyHashValue;
1198 + value -= subValue;
1203 +static void MatchFinder_Normalize(CMatchFinder *p)
1205 + UInt32 subValue = MatchFinder_GetSubValue(p);
1206 + MatchFinder_Normalize3(subValue, p->hash, p->hashSizeSum + p->numSons);
1207 + MatchFinder_ReduceOffsets(p, subValue);
1210 +static void MatchFinder_CheckLimits(CMatchFinder *p)
1212 + if (p->pos == kMaxValForNormalize)
1213 + MatchFinder_Normalize(p);
1214 + if (!p->streamEndWasReached && p->keepSizeAfter == p->streamPos - p->pos)
1215 + MatchFinder_CheckAndMoveAndRead(p);
1216 + if (p->cyclicBufferPos == p->cyclicBufferSize)
1217 + p->cyclicBufferPos = 0;
1218 + MatchFinder_SetLimits(p);
1221 +static UInt32 * Hc_GetMatchesSpec(UInt32 lenLimit, UInt32 curMatch, UInt32 pos, const Byte *cur, CLzRef *son,
1222 + UInt32 _cyclicBufferPos, UInt32 _cyclicBufferSize, UInt32 cutValue,
1223 + UInt32 *distances, UInt32 maxLen)
1225 + son[_cyclicBufferPos] = curMatch;
1228 + UInt32 delta = pos - curMatch;
1229 + if (cutValue-- == 0 || delta >= _cyclicBufferSize)
1232 + const Byte *pb = cur - delta;
1233 + curMatch = son[_cyclicBufferPos - delta + ((delta > _cyclicBufferPos) ? _cyclicBufferSize : 0)];
1234 + if (pb[maxLen] == cur[maxLen] && *pb == *cur)
1237 + while(++len != lenLimit)
1238 + if (pb[len] != cur[len])
1242 + *distances++ = maxLen = len;
1243 + *distances++ = delta - 1;
1244 + if (len == lenLimit)
1252 +UInt32 * GetMatchesSpec1(UInt32 lenLimit, UInt32 curMatch, UInt32 pos, const Byte *cur, CLzRef *son,
1253 + UInt32 _cyclicBufferPos, UInt32 _cyclicBufferSize, UInt32 cutValue,
1254 + UInt32 *distances, UInt32 maxLen)
1256 + CLzRef *ptr0 = son + (_cyclicBufferPos << 1) + 1;
1257 + CLzRef *ptr1 = son + (_cyclicBufferPos << 1);
1258 + UInt32 len0 = 0, len1 = 0;
1261 + UInt32 delta = pos - curMatch;
1262 + if (cutValue-- == 0 || delta >= _cyclicBufferSize)
1264 + *ptr0 = *ptr1 = kEmptyHashValue;
1268 + CLzRef *pair = son + ((_cyclicBufferPos - delta + ((delta > _cyclicBufferPos) ? _cyclicBufferSize : 0)) << 1);
1269 + const Byte *pb = cur - delta;
1270 + UInt32 len = (len0 < len1 ? len0 : len1);
1271 + if (pb[len] == cur[len])
1273 + if (++len != lenLimit && pb[len] == cur[len])
1274 + while(++len != lenLimit)
1275 + if (pb[len] != cur[len])
1279 + *distances++ = maxLen = len;
1280 + *distances++ = delta - 1;
1281 + if (len == lenLimit)
1289 + if (pb[len] < cur[len])
1307 +static void SkipMatchesSpec(UInt32 lenLimit, UInt32 curMatch, UInt32 pos, const Byte *cur, CLzRef *son,
1308 + UInt32 _cyclicBufferPos, UInt32 _cyclicBufferSize, UInt32 cutValue)
1310 + CLzRef *ptr0 = son + (_cyclicBufferPos << 1) + 1;
1311 + CLzRef *ptr1 = son + (_cyclicBufferPos << 1);
1312 + UInt32 len0 = 0, len1 = 0;
1315 + UInt32 delta = pos - curMatch;
1316 + if (cutValue-- == 0 || delta >= _cyclicBufferSize)
1318 + *ptr0 = *ptr1 = kEmptyHashValue;
1322 + CLzRef *pair = son + ((_cyclicBufferPos - delta + ((delta > _cyclicBufferPos) ? _cyclicBufferSize : 0)) << 1);
1323 + const Byte *pb = cur - delta;
1324 + UInt32 len = (len0 < len1 ? len0 : len1);
1325 + if (pb[len] == cur[len])
1327 + while(++len != lenLimit)
1328 + if (pb[len] != cur[len])
1331 + if (len == lenLimit)
1339 + if (pb[len] < cur[len])
1358 + ++p->cyclicBufferPos; \
1360 + if (++p->pos == p->posLimit) MatchFinder_CheckLimits(p);
1362 +#define MOVE_POS_RET MOVE_POS return offset;
1364 +static void MatchFinder_MovePos(CMatchFinder *p) { MOVE_POS; }
1366 +#define GET_MATCHES_HEADER2(minLen, ret_op) \
1367 + UInt32 lenLimit; UInt32 hashValue; const Byte *cur; UInt32 curMatch; \
1368 + lenLimit = p->lenLimit; { if (lenLimit < minLen) { MatchFinder_MovePos(p); ret_op; }} \
1371 +#define GET_MATCHES_HEADER(minLen) GET_MATCHES_HEADER2(minLen, return 0)
1372 +#define SKIP_HEADER(minLen) GET_MATCHES_HEADER2(minLen, continue)
1374 +#define MF_PARAMS(p) p->pos, p->buffer, p->son, p->cyclicBufferPos, p->cyclicBufferSize, p->cutValue
1376 +#define GET_MATCHES_FOOTER(offset, maxLen) \
1377 + offset = (UInt32)(GetMatchesSpec1(lenLimit, curMatch, MF_PARAMS(p), \
1378 + distances + offset, maxLen) - distances); MOVE_POS_RET;
1380 +#define SKIP_FOOTER \
1381 + SkipMatchesSpec(lenLimit, curMatch, MF_PARAMS(p)); MOVE_POS;
1383 +static UInt32 Bt2_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances)
1386 + GET_MATCHES_HEADER(2)
1388 + curMatch = p->hash[hashValue];
1389 + p->hash[hashValue] = p->pos;
1391 + GET_MATCHES_FOOTER(offset, 1)
1394 +UInt32 Bt3Zip_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances)
1397 + GET_MATCHES_HEADER(3)
1399 + curMatch = p->hash[hashValue];
1400 + p->hash[hashValue] = p->pos;
1402 + GET_MATCHES_FOOTER(offset, 2)
1405 +static UInt32 Bt3_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances)
1407 + UInt32 hash2Value, delta2, maxLen, offset;
1408 + GET_MATCHES_HEADER(3)
1412 + delta2 = p->pos - p->hash[hash2Value];
1413 + curMatch = p->hash[kFix3HashSize + hashValue];
1415 + p->hash[hash2Value] =
1416 + p->hash[kFix3HashSize + hashValue] = p->pos;
1421 + if (delta2 < p->cyclicBufferSize && *(cur - delta2) == *cur)
1423 + for (; maxLen != lenLimit; maxLen++)
1424 + if (cur[(ptrdiff_t)maxLen - delta2] != cur[maxLen])
1426 + distances[0] = maxLen;
1427 + distances[1] = delta2 - 1;
1429 + if (maxLen == lenLimit)
1431 + SkipMatchesSpec(lenLimit, curMatch, MF_PARAMS(p));
1435 + GET_MATCHES_FOOTER(offset, maxLen)
1438 +static UInt32 Bt4_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances)
1440 + UInt32 hash2Value, hash3Value, delta2, delta3, maxLen, offset;
1441 + GET_MATCHES_HEADER(4)
1445 + delta2 = p->pos - p->hash[ hash2Value];
1446 + delta3 = p->pos - p->hash[kFix3HashSize + hash3Value];
1447 + curMatch = p->hash[kFix4HashSize + hashValue];
1449 + p->hash[ hash2Value] =
1450 + p->hash[kFix3HashSize + hash3Value] =
1451 + p->hash[kFix4HashSize + hashValue] = p->pos;
1455 + if (delta2 < p->cyclicBufferSize && *(cur - delta2) == *cur)
1457 + distances[0] = maxLen = 2;
1458 + distances[1] = delta2 - 1;
1461 + if (delta2 != delta3 && delta3 < p->cyclicBufferSize && *(cur - delta3) == *cur)
1464 + distances[offset + 1] = delta3 - 1;
1470 + for (; maxLen != lenLimit; maxLen++)
1471 + if (cur[(ptrdiff_t)maxLen - delta2] != cur[maxLen])
1473 + distances[offset - 2] = maxLen;
1474 + if (maxLen == lenLimit)
1476 + SkipMatchesSpec(lenLimit, curMatch, MF_PARAMS(p));
1482 + GET_MATCHES_FOOTER(offset, maxLen)
1485 +static UInt32 Hc4_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances)
1487 + UInt32 hash2Value, hash3Value, delta2, delta3, maxLen, offset;
1488 + GET_MATCHES_HEADER(4)
1492 + delta2 = p->pos - p->hash[ hash2Value];
1493 + delta3 = p->pos - p->hash[kFix3HashSize + hash3Value];
1494 + curMatch = p->hash[kFix4HashSize + hashValue];
1496 + p->hash[ hash2Value] =
1497 + p->hash[kFix3HashSize + hash3Value] =
1498 + p->hash[kFix4HashSize + hashValue] = p->pos;
1502 + if (delta2 < p->cyclicBufferSize && *(cur - delta2) == *cur)
1504 + distances[0] = maxLen = 2;
1505 + distances[1] = delta2 - 1;
1508 + if (delta2 != delta3 && delta3 < p->cyclicBufferSize && *(cur - delta3) == *cur)
1511 + distances[offset + 1] = delta3 - 1;
1517 + for (; maxLen != lenLimit; maxLen++)
1518 + if (cur[(ptrdiff_t)maxLen - delta2] != cur[maxLen])
1520 + distances[offset - 2] = maxLen;
1521 + if (maxLen == lenLimit)
1523 + p->son[p->cyclicBufferPos] = curMatch;
1529 + offset = (UInt32)(Hc_GetMatchesSpec(lenLimit, curMatch, MF_PARAMS(p),
1530 + distances + offset, maxLen) - (distances));
1534 +UInt32 Hc3Zip_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances)
1537 + GET_MATCHES_HEADER(3)
1539 + curMatch = p->hash[hashValue];
1540 + p->hash[hashValue] = p->pos;
1541 + offset = (UInt32)(Hc_GetMatchesSpec(lenLimit, curMatch, MF_PARAMS(p),
1542 + distances, 2) - (distances));
1546 +static void Bt2_MatchFinder_Skip(CMatchFinder *p, UInt32 num)
1552 + curMatch = p->hash[hashValue];
1553 + p->hash[hashValue] = p->pos;
1556 + while (--num != 0);
1559 +void Bt3Zip_MatchFinder_Skip(CMatchFinder *p, UInt32 num)
1565 + curMatch = p->hash[hashValue];
1566 + p->hash[hashValue] = p->pos;
1569 + while (--num != 0);
1572 +static void Bt3_MatchFinder_Skip(CMatchFinder *p, UInt32 num)
1576 + UInt32 hash2Value;
1579 + curMatch = p->hash[kFix3HashSize + hashValue];
1580 + p->hash[hash2Value] =
1581 + p->hash[kFix3HashSize + hashValue] = p->pos;
1584 + while (--num != 0);
1587 +static void Bt4_MatchFinder_Skip(CMatchFinder *p, UInt32 num)
1591 + UInt32 hash2Value, hash3Value;
1594 + curMatch = p->hash[kFix4HashSize + hashValue];
1595 + p->hash[ hash2Value] =
1596 + p->hash[kFix3HashSize + hash3Value] = p->pos;
1597 + p->hash[kFix4HashSize + hashValue] = p->pos;
1600 + while (--num != 0);
1603 +static void Hc4_MatchFinder_Skip(CMatchFinder *p, UInt32 num)
1607 + UInt32 hash2Value, hash3Value;
1610 + curMatch = p->hash[kFix4HashSize + hashValue];
1611 + p->hash[ hash2Value] =
1612 + p->hash[kFix3HashSize + hash3Value] =
1613 + p->hash[kFix4HashSize + hashValue] = p->pos;
1614 + p->son[p->cyclicBufferPos] = curMatch;
1617 + while (--num != 0);
1620 +void Hc3Zip_MatchFinder_Skip(CMatchFinder *p, UInt32 num)
1626 + curMatch = p->hash[hashValue];
1627 + p->hash[hashValue] = p->pos;
1628 + p->son[p->cyclicBufferPos] = curMatch;
1631 + while (--num != 0);
1634 +void MatchFinder_CreateVTable(CMatchFinder *p, IMatchFinder *vTable)
1636 + vTable->Init = (Mf_Init_Func)MatchFinder_Init;
1637 + vTable->GetIndexByte = (Mf_GetIndexByte_Func)MatchFinder_GetIndexByte;
1638 + vTable->GetNumAvailableBytes = (Mf_GetNumAvailableBytes_Func)MatchFinder_GetNumAvailableBytes;
1639 + vTable->GetPointerToCurrentPos = (Mf_GetPointerToCurrentPos_Func)MatchFinder_GetPointerToCurrentPos;
1642 + vTable->GetMatches = (Mf_GetMatches_Func)Hc4_MatchFinder_GetMatches;
1643 + vTable->Skip = (Mf_Skip_Func)Hc4_MatchFinder_Skip;
1645 + else if (p->numHashBytes == 2)
1647 + vTable->GetMatches = (Mf_GetMatches_Func)Bt2_MatchFinder_GetMatches;
1648 + vTable->Skip = (Mf_Skip_Func)Bt2_MatchFinder_Skip;
1650 + else if (p->numHashBytes == 3)
1652 + vTable->GetMatches = (Mf_GetMatches_Func)Bt3_MatchFinder_GetMatches;
1653 + vTable->Skip = (Mf_Skip_Func)Bt3_MatchFinder_Skip;
1657 + vTable->GetMatches = (Mf_GetMatches_Func)Bt4_MatchFinder_GetMatches;
1658 + vTable->Skip = (Mf_Skip_Func)Bt4_MatchFinder_Skip;
1662 +++ b/jffsX-utils/lzma/LzmaDec.c
1664 +/* LzmaDec.c -- LZMA Decoder
1666 +Copyright (c) 1999-2008 Igor Pavlov
1667 +Read LzmaDec.h for license options */
1669 +#include "LzmaDec.h"
1671 +#include <string.h>
1673 +#define kNumTopBits 24
1674 +#define kTopValue ((UInt32)1 << kNumTopBits)
1676 +#define kNumBitModelTotalBits 11
1677 +#define kBitModelTotal (1 << kNumBitModelTotalBits)
1678 +#define kNumMoveBits 5
1680 +#define RC_INIT_SIZE 5
1682 +#define NORMALIZE if (range < kTopValue) { range <<= 8; code = (code << 8) | (*buf++); }
1684 +#define IF_BIT_0(p) ttt = *(p); NORMALIZE; bound = (range >> kNumBitModelTotalBits) * ttt; if (code < bound)
1685 +#define UPDATE_0(p) range = bound; *(p) = (CLzmaProb)(ttt + ((kBitModelTotal - ttt) >> kNumMoveBits));
1686 +#define UPDATE_1(p) range -= bound; code -= bound; *(p) = (CLzmaProb)(ttt - (ttt >> kNumMoveBits));
1687 +#define GET_BIT2(p, i, A0, A1) IF_BIT_0(p) \
1688 + { UPDATE_0(p); i = (i + i); A0; } else \
1689 + { UPDATE_1(p); i = (i + i) + 1; A1; }
1690 +#define GET_BIT(p, i) GET_BIT2(p, i, ; , ;)
1692 +#define TREE_GET_BIT(probs, i) { GET_BIT((probs + i), i); }
1693 +#define TREE_DECODE(probs, limit, i) \
1694 + { i = 1; do { TREE_GET_BIT(probs, i); } while (i < limit); i -= limit; }
1696 +/* #define _LZMA_SIZE_OPT */
1698 +#ifdef _LZMA_SIZE_OPT
1699 +#define TREE_6_DECODE(probs, i) TREE_DECODE(probs, (1 << 6), i)
1701 +#define TREE_6_DECODE(probs, i) \
1703 + TREE_GET_BIT(probs, i); \
1704 + TREE_GET_BIT(probs, i); \
1705 + TREE_GET_BIT(probs, i); \
1706 + TREE_GET_BIT(probs, i); \
1707 + TREE_GET_BIT(probs, i); \
1708 + TREE_GET_BIT(probs, i); \
1712 +#define NORMALIZE_CHECK if (range < kTopValue) { if (buf >= bufLimit) return DUMMY_ERROR; range <<= 8; code = (code << 8) | (*buf++); }
1714 +#define IF_BIT_0_CHECK(p) ttt = *(p); NORMALIZE_CHECK; bound = (range >> kNumBitModelTotalBits) * ttt; if (code < bound)
1715 +#define UPDATE_0_CHECK range = bound;
1716 +#define UPDATE_1_CHECK range -= bound; code -= bound;
1717 +#define GET_BIT2_CHECK(p, i, A0, A1) IF_BIT_0_CHECK(p) \
1718 + { UPDATE_0_CHECK; i = (i + i); A0; } else \
1719 + { UPDATE_1_CHECK; i = (i + i) + 1; A1; }
1720 +#define GET_BIT_CHECK(p, i) GET_BIT2_CHECK(p, i, ; , ;)
1721 +#define TREE_DECODE_CHECK(probs, limit, i) \
1722 + { i = 1; do { GET_BIT_CHECK(probs + i, i) } while(i < limit); i -= limit; }
1725 +#define kNumPosBitsMax 4
1726 +#define kNumPosStatesMax (1 << kNumPosBitsMax)
1728 +#define kLenNumLowBits 3
1729 +#define kLenNumLowSymbols (1 << kLenNumLowBits)
1730 +#define kLenNumMidBits 3
1731 +#define kLenNumMidSymbols (1 << kLenNumMidBits)
1732 +#define kLenNumHighBits 8
1733 +#define kLenNumHighSymbols (1 << kLenNumHighBits)
1735 +#define LenChoice 0
1736 +#define LenChoice2 (LenChoice + 1)
1737 +#define LenLow (LenChoice2 + 1)
1738 +#define LenMid (LenLow + (kNumPosStatesMax << kLenNumLowBits))
1739 +#define LenHigh (LenMid + (kNumPosStatesMax << kLenNumMidBits))
1740 +#define kNumLenProbs (LenHigh + kLenNumHighSymbols)
1743 +#define kNumStates 12
1744 +#define kNumLitStates 7
1746 +#define kStartPosModelIndex 4
1747 +#define kEndPosModelIndex 14
1748 +#define kNumFullDistances (1 << (kEndPosModelIndex >> 1))
1750 +#define kNumPosSlotBits 6
1751 +#define kNumLenToPosStates 4
1753 +#define kNumAlignBits 4
1754 +#define kAlignTableSize (1 << kNumAlignBits)
1756 +#define kMatchMinLen 2
1757 +#define kMatchSpecLenStart (kMatchMinLen + kLenNumLowSymbols + kLenNumMidSymbols + kLenNumHighSymbols)
1760 +#define IsRep (IsMatch + (kNumStates << kNumPosBitsMax))
1761 +#define IsRepG0 (IsRep + kNumStates)
1762 +#define IsRepG1 (IsRepG0 + kNumStates)
1763 +#define IsRepG2 (IsRepG1 + kNumStates)
1764 +#define IsRep0Long (IsRepG2 + kNumStates)
1765 +#define PosSlot (IsRep0Long + (kNumStates << kNumPosBitsMax))
1766 +#define SpecPos (PosSlot + (kNumLenToPosStates << kNumPosSlotBits))
1767 +#define Align (SpecPos + kNumFullDistances - kEndPosModelIndex)
1768 +#define LenCoder (Align + kAlignTableSize)
1769 +#define RepLenCoder (LenCoder + kNumLenProbs)
1770 +#define Literal (RepLenCoder + kNumLenProbs)
1772 +#define LZMA_BASE_SIZE 1846
1773 +#define LZMA_LIT_SIZE 768
1775 +#define LzmaProps_GetNumProbs(p) ((UInt32)LZMA_BASE_SIZE + (LZMA_LIT_SIZE << ((p)->lc + (p)->lp)))
1777 +#if Literal != LZMA_BASE_SIZE
1778 +StopCompilingDueBUG
1782 +#define LZMA_STREAM_WAS_FINISHED_ID (-1)
1783 +#define LZMA_SPEC_LEN_OFFSET (-3)
1786 +Byte kLiteralNextStates[kNumStates * 2] =
1788 + 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 4, 5,
1789 + 7, 7, 7, 7, 7, 7, 7, 10, 10, 10, 10, 10
1792 +#define LZMA_DIC_MIN (1 << 12)
1794 +/* First LZMA-symbol is always decoded.
1795 +And it decodes new LZMA-symbols while (buf < bufLimit), but "buf" is without last normalization
1801 + < kMatchSpecLenStart : normal remain
1802 + = kMatchSpecLenStart : finished
1803 + = kMatchSpecLenStart + 1 : Flush marker
1804 + = kMatchSpecLenStart + 2 : State Init Marker
1807 +static int MY_FAST_CALL LzmaDec_DecodeReal(CLzmaDec *p, SizeT limit, const Byte *bufLimit)
1809 + CLzmaProb *probs = p->probs;
1811 + unsigned state = p->state;
1812 + UInt32 rep0 = p->reps[0], rep1 = p->reps[1], rep2 = p->reps[2], rep3 = p->reps[3];
1813 + unsigned pbMask = ((unsigned)1 << (p->prop.pb)) - 1;
1814 + unsigned lpMask = ((unsigned)1 << (p->prop.lp)) - 1;
1815 + unsigned lc = p->prop.lc;
1817 + Byte *dic = p->dic;
1818 + SizeT dicBufSize = p->dicBufSize;
1819 + SizeT dicPos = p->dicPos;
1821 + UInt32 processedPos = p->processedPos;
1822 + UInt32 checkDicSize = p->checkDicSize;
1825 + const Byte *buf = p->buf;
1826 + UInt32 range = p->range;
1827 + UInt32 code = p->code;
1834 + unsigned posState = processedPos & pbMask;
1836 + prob = probs + IsMatch + (state << kNumPosBitsMax) + posState;
1841 + prob = probs + Literal;
1842 + if (checkDicSize != 0 || processedPos != 0)
1843 + prob += (LZMA_LIT_SIZE * (((processedPos & lpMask) << lc) +
1844 + (dic[(dicPos == 0 ? dicBufSize : dicPos) - 1] >> (8 - lc))));
1846 + if (state < kNumLitStates)
1849 + do { GET_BIT(prob + symbol, symbol) } while (symbol < 0x100);
1853 + unsigned matchByte = p->dic[(dicPos - rep0) + ((dicPos < rep0) ? dicBufSize : 0)];
1854 + unsigned offs = 0x100;
1859 + CLzmaProb *probLit;
1861 + bit = (matchByte & offs);
1862 + probLit = prob + offs + bit + symbol;
1863 + GET_BIT2(probLit, symbol, offs &= ~bit, offs &= bit)
1865 + while (symbol < 0x100);
1867 + dic[dicPos++] = (Byte)symbol;
1870 + state = kLiteralNextStates[state];
1871 + /* if (state < 4) state = 0; else if (state < 10) state -= 3; else state -= 6; */
1877 + prob = probs + IsRep + state;
1881 + state += kNumStates;
1882 + prob = probs + LenCoder;
1887 + if (checkDicSize == 0 && processedPos == 0)
1888 + return SZ_ERROR_DATA;
1889 + prob = probs + IsRepG0 + state;
1893 + prob = probs + IsRep0Long + (state << kNumPosBitsMax) + posState;
1897 + dic[dicPos] = dic[(dicPos - rep0) + ((dicPos < rep0) ? dicBufSize : 0)];
1900 + state = state < kNumLitStates ? 9 : 11;
1909 + prob = probs + IsRepG1 + state;
1918 + prob = probs + IsRepG2 + state;
1935 + state = state < kNumLitStates ? 8 : 11;
1936 + prob = probs + RepLenCoder;
1939 + unsigned limit, offset;
1940 + CLzmaProb *probLen = prob + LenChoice;
1943 + UPDATE_0(probLen);
1944 + probLen = prob + LenLow + (posState << kLenNumLowBits);
1946 + limit = (1 << kLenNumLowBits);
1950 + UPDATE_1(probLen);
1951 + probLen = prob + LenChoice2;
1954 + UPDATE_0(probLen);
1955 + probLen = prob + LenMid + (posState << kLenNumMidBits);
1956 + offset = kLenNumLowSymbols;
1957 + limit = (1 << kLenNumMidBits);
1961 + UPDATE_1(probLen);
1962 + probLen = prob + LenHigh;
1963 + offset = kLenNumLowSymbols + kLenNumMidSymbols;
1964 + limit = (1 << kLenNumHighBits);
1967 + TREE_DECODE(probLen, limit, len);
1971 + if (state >= kNumStates)
1974 + prob = probs + PosSlot +
1975 + ((len < kNumLenToPosStates ? len : kNumLenToPosStates - 1) << kNumPosSlotBits);
1976 + TREE_6_DECODE(prob, distance);
1977 + if (distance >= kStartPosModelIndex)
1979 + unsigned posSlot = (unsigned)distance;
1980 + int numDirectBits = (int)(((distance >> 1) - 1));
1981 + distance = (2 | (distance & 1));
1982 + if (posSlot < kEndPosModelIndex)
1984 + distance <<= numDirectBits;
1985 + prob = probs + SpecPos + distance - posSlot - 1;
1991 + GET_BIT2(prob + i, i, ; , distance |= mask);
1994 + while(--numDirectBits != 0);
1999 + numDirectBits -= kNumAlignBits;
2008 + t = (0 - ((UInt32)code >> 31)); /* (UInt32)((Int32)code >> 31) */
2009 + distance = (distance << 1) + (t + 1);
2010 + code += range & t;
2014 + if (code >= range)
2021 + while (--numDirectBits != 0);
2022 + prob = probs + Align;
2023 + distance <<= kNumAlignBits;
2026 + GET_BIT2(prob + i, i, ; , distance |= 1);
2027 + GET_BIT2(prob + i, i, ; , distance |= 2);
2028 + GET_BIT2(prob + i, i, ; , distance |= 4);
2029 + GET_BIT2(prob + i, i, ; , distance |= 8);
2031 + if (distance == (UInt32)0xFFFFFFFF)
2033 + len += kMatchSpecLenStart;
2034 + state -= kNumStates;
2042 + rep0 = distance + 1;
2043 + if (checkDicSize == 0)
2045 + if (distance >= processedPos)
2046 + return SZ_ERROR_DATA;
2048 + else if (distance >= checkDicSize)
2049 + return SZ_ERROR_DATA;
2050 + state = (state < kNumStates + kNumLitStates) ? kNumLitStates : kNumLitStates + 3;
2051 + /* state = kLiteralNextStates[state]; */
2054 + len += kMatchMinLen;
2057 + SizeT rem = limit - dicPos;
2058 + unsigned curLen = ((rem < len) ? (unsigned)rem : len);
2059 + SizeT pos = (dicPos - rep0) + ((dicPos < rep0) ? dicBufSize : 0);
2061 + processedPos += curLen;
2064 + if (pos + curLen <= dicBufSize)
2066 + Byte *dest = dic + dicPos;
2067 + ptrdiff_t src = (ptrdiff_t)pos - (ptrdiff_t)dicPos;
2068 + const Byte *lim = dest + curLen;
2071 + *(dest) = (Byte)*(dest + src);
2072 + while (++dest != lim);
2078 + dic[dicPos++] = dic[pos];
2079 + if (++pos == dicBufSize)
2082 + while (--curLen != 0);
2087 + while (dicPos < limit && buf < bufLimit);
2092 + p->remainLen = len;
2093 + p->dicPos = dicPos;
2094 + p->processedPos = processedPos;
2095 + p->reps[0] = rep0;
2096 + p->reps[1] = rep1;
2097 + p->reps[2] = rep2;
2098 + p->reps[3] = rep3;
2104 +static void MY_FAST_CALL LzmaDec_WriteRem(CLzmaDec *p, SizeT limit)
2106 + if (p->remainLen != 0 && p->remainLen < kMatchSpecLenStart)
2108 + Byte *dic = p->dic;
2109 + SizeT dicPos = p->dicPos;
2110 + SizeT dicBufSize = p->dicBufSize;
2111 + unsigned len = p->remainLen;
2112 + UInt32 rep0 = p->reps[0];
2113 + if (limit - dicPos < len)
2114 + len = (unsigned)(limit - dicPos);
2116 + if (p->checkDicSize == 0 && p->prop.dicSize - p->processedPos <= len)
2117 + p->checkDicSize = p->prop.dicSize;
2119 + p->processedPos += len;
2120 + p->remainLen -= len;
2121 + while (len-- != 0)
2123 + dic[dicPos] = dic[(dicPos - rep0) + ((dicPos < rep0) ? dicBufSize : 0)];
2126 + p->dicPos = dicPos;
2130 +/* LzmaDec_DecodeReal2 decodes LZMA-symbols and sets p->needFlush and p->needInit, if required. */
2132 +static int MY_FAST_CALL LzmaDec_DecodeReal2(CLzmaDec *p, SizeT limit, const Byte *bufLimit)
2136 + SizeT limit2 = limit;
2137 + if (p->checkDicSize == 0)
2139 + UInt32 rem = p->prop.dicSize - p->processedPos;
2140 + if (limit - p->dicPos > rem)
2141 + limit2 = p->dicPos + rem;
2143 + RINOK(LzmaDec_DecodeReal(p, limit2, bufLimit));
2144 + if (p->processedPos >= p->prop.dicSize)
2145 + p->checkDicSize = p->prop.dicSize;
2146 + LzmaDec_WriteRem(p, limit);
2148 + while (p->dicPos < limit && p->buf < bufLimit && p->remainLen < kMatchSpecLenStart);
2150 + if (p->remainLen > kMatchSpecLenStart)
2152 + p->remainLen = kMatchSpecLenStart;
2159 + DUMMY_ERROR, /* unexpected end of input stream */
2165 +static ELzmaDummy LzmaDec_TryDummy(const CLzmaDec *p, const Byte *buf, SizeT inSize)
2167 + UInt32 range = p->range;
2168 + UInt32 code = p->code;
2169 + const Byte *bufLimit = buf + inSize;
2170 + CLzmaProb *probs = p->probs;
2171 + unsigned state = p->state;
2178 + unsigned posState = (p->processedPos) & ((1 << p->prop.pb) - 1);
2180 + prob = probs + IsMatch + (state << kNumPosBitsMax) + posState;
2181 + IF_BIT_0_CHECK(prob)
2185 + /* if (bufLimit - buf >= 7) return DUMMY_LIT; */
2187 + prob = probs + Literal;
2188 + if (p->checkDicSize != 0 || p->processedPos != 0)
2189 + prob += (LZMA_LIT_SIZE *
2190 + ((((p->processedPos) & ((1 << (p->prop.lp)) - 1)) << p->prop.lc) +
2191 + (p->dic[(p->dicPos == 0 ? p->dicBufSize : p->dicPos) - 1] >> (8 - p->prop.lc))));
2193 + if (state < kNumLitStates)
2195 + unsigned symbol = 1;
2196 + do { GET_BIT_CHECK(prob + symbol, symbol) } while (symbol < 0x100);
2200 + unsigned matchByte = p->dic[p->dicPos - p->reps[0] +
2201 + ((p->dicPos < p->reps[0]) ? p->dicBufSize : 0)];
2202 + unsigned offs = 0x100;
2203 + unsigned symbol = 1;
2207 + CLzmaProb *probLit;
2209 + bit = (matchByte & offs);
2210 + probLit = prob + offs + bit + symbol;
2211 + GET_BIT2_CHECK(probLit, symbol, offs &= ~bit, offs &= bit)
2213 + while (symbol < 0x100);
2222 + prob = probs + IsRep + state;
2223 + IF_BIT_0_CHECK(prob)
2227 + prob = probs + LenCoder;
2228 + res = DUMMY_MATCH;
2234 + prob = probs + IsRepG0 + state;
2235 + IF_BIT_0_CHECK(prob)
2238 + prob = probs + IsRep0Long + (state << kNumPosBitsMax) + posState;
2239 + IF_BIT_0_CHECK(prob)
2253 + prob = probs + IsRepG1 + state;
2254 + IF_BIT_0_CHECK(prob)
2261 + prob = probs + IsRepG2 + state;
2262 + IF_BIT_0_CHECK(prob)
2272 + state = kNumStates;
2273 + prob = probs + RepLenCoder;
2276 + unsigned limit, offset;
2277 + CLzmaProb *probLen = prob + LenChoice;
2278 + IF_BIT_0_CHECK(probLen)
2281 + probLen = prob + LenLow + (posState << kLenNumLowBits);
2283 + limit = 1 << kLenNumLowBits;
2288 + probLen = prob + LenChoice2;
2289 + IF_BIT_0_CHECK(probLen)
2292 + probLen = prob + LenMid + (posState << kLenNumMidBits);
2293 + offset = kLenNumLowSymbols;
2294 + limit = 1 << kLenNumMidBits;
2299 + probLen = prob + LenHigh;
2300 + offset = kLenNumLowSymbols + kLenNumMidSymbols;
2301 + limit = 1 << kLenNumHighBits;
2304 + TREE_DECODE_CHECK(probLen, limit, len);
2311 + prob = probs + PosSlot +
2312 + ((len < kNumLenToPosStates ? len : kNumLenToPosStates - 1) <<
2314 + TREE_DECODE_CHECK(prob, 1 << kNumPosSlotBits, posSlot);
2315 + if (posSlot >= kStartPosModelIndex)
2317 + int numDirectBits = ((posSlot >> 1) - 1);
2319 + /* if (bufLimit - buf >= 8) return DUMMY_MATCH; */
2321 + if (posSlot < kEndPosModelIndex)
2323 + prob = probs + SpecPos + ((2 | (posSlot & 1)) << numDirectBits) - posSlot - 1;
2327 + numDirectBits -= kNumAlignBits;
2332 + code -= range & (((code - range) >> 31) - 1);
2333 + /* if (code >= range) code -= range; */
2335 + while (--numDirectBits != 0);
2336 + prob = probs + Align;
2337 + numDirectBits = kNumAlignBits;
2343 + GET_BIT_CHECK(prob + i, i);
2345 + while(--numDirectBits != 0);
2356 +static void LzmaDec_InitRc(CLzmaDec *p, const Byte *data)
2358 + p->code = ((UInt32)data[1] << 24) | ((UInt32)data[2] << 16) | ((UInt32)data[3] << 8) | ((UInt32)data[4]);
2359 + p->range = 0xFFFFFFFF;
2363 +static void LzmaDec_InitDicAndState(CLzmaDec *p, Bool initDic, Bool initState)
2367 + p->tempBufSize = 0;
2371 + p->processedPos = 0;
2372 + p->checkDicSize = 0;
2373 + p->needInitState = 1;
2376 + p->needInitState = 1;
2379 +void LzmaDec_Init(CLzmaDec *p)
2382 + LzmaDec_InitDicAndState(p, True, True);
2385 +static void LzmaDec_InitStateReal(CLzmaDec *p)
2387 + UInt32 numProbs = Literal + ((UInt32)LZMA_LIT_SIZE << (p->prop.lc + p->prop.lp));
2389 + CLzmaProb *probs = p->probs;
2390 + for (i = 0; i < numProbs; i++)
2391 + probs[i] = kBitModelTotal >> 1;
2392 + p->reps[0] = p->reps[1] = p->reps[2] = p->reps[3] = 1;
2394 + p->needInitState = 0;
2397 +SRes LzmaDec_DecodeToDic(CLzmaDec *p, SizeT dicLimit, const Byte *src, SizeT *srcLen,
2398 + ELzmaFinishMode finishMode, ELzmaStatus *status)
2400 + SizeT inSize = *srcLen;
2402 + LzmaDec_WriteRem(p, dicLimit);
2404 + *status = LZMA_STATUS_NOT_SPECIFIED;
2406 + while (p->remainLen != kMatchSpecLenStart)
2408 + int checkEndMarkNow;
2410 + if (p->needFlush != 0)
2412 + for (; inSize > 0 && p->tempBufSize < RC_INIT_SIZE; (*srcLen)++, inSize--)
2413 + p->tempBuf[p->tempBufSize++] = *src++;
2414 + if (p->tempBufSize < RC_INIT_SIZE)
2416 + *status = LZMA_STATUS_NEEDS_MORE_INPUT;
2419 + if (p->tempBuf[0] != 0)
2420 + return SZ_ERROR_DATA;
2422 + LzmaDec_InitRc(p, p->tempBuf);
2423 + p->tempBufSize = 0;
2426 + checkEndMarkNow = 0;
2427 + if (p->dicPos >= dicLimit)
2429 + if (p->remainLen == 0 && p->code == 0)
2431 + *status = LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK;
2434 + if (finishMode == LZMA_FINISH_ANY)
2436 + *status = LZMA_STATUS_NOT_FINISHED;
2439 + if (p->remainLen != 0)
2441 + *status = LZMA_STATUS_NOT_FINISHED;
2442 + return SZ_ERROR_DATA;
2444 + checkEndMarkNow = 1;
2447 + if (p->needInitState)
2448 + LzmaDec_InitStateReal(p);
2450 + if (p->tempBufSize == 0)
2453 + const Byte *bufLimit;
2454 + if (inSize < LZMA_REQUIRED_INPUT_MAX || checkEndMarkNow)
2456 + int dummyRes = LzmaDec_TryDummy(p, src, inSize);
2457 + if (dummyRes == DUMMY_ERROR)
2459 + memcpy(p->tempBuf, src, inSize);
2460 + p->tempBufSize = (unsigned)inSize;
2461 + (*srcLen) += inSize;
2462 + *status = LZMA_STATUS_NEEDS_MORE_INPUT;
2465 + if (checkEndMarkNow && dummyRes != DUMMY_MATCH)
2467 + *status = LZMA_STATUS_NOT_FINISHED;
2468 + return SZ_ERROR_DATA;
2473 + bufLimit = src + inSize - LZMA_REQUIRED_INPUT_MAX;
2475 + if (LzmaDec_DecodeReal2(p, dicLimit, bufLimit) != 0)
2476 + return SZ_ERROR_DATA;
2477 + processed = p->buf - src;
2478 + (*srcLen) += processed;
2480 + inSize -= processed;
2484 + unsigned rem = p->tempBufSize, lookAhead = 0;
2485 + while (rem < LZMA_REQUIRED_INPUT_MAX && lookAhead < inSize)
2486 + p->tempBuf[rem++] = src[lookAhead++];
2487 + p->tempBufSize = rem;
2488 + if (rem < LZMA_REQUIRED_INPUT_MAX || checkEndMarkNow)
2490 + int dummyRes = LzmaDec_TryDummy(p, p->tempBuf, rem);
2491 + if (dummyRes == DUMMY_ERROR)
2493 + (*srcLen) += lookAhead;
2494 + *status = LZMA_STATUS_NEEDS_MORE_INPUT;
2497 + if (checkEndMarkNow && dummyRes != DUMMY_MATCH)
2499 + *status = LZMA_STATUS_NOT_FINISHED;
2500 + return SZ_ERROR_DATA;
2503 + p->buf = p->tempBuf;
2504 + if (LzmaDec_DecodeReal2(p, dicLimit, p->buf) != 0)
2505 + return SZ_ERROR_DATA;
2506 + lookAhead -= (rem - (unsigned)(p->buf - p->tempBuf));
2507 + (*srcLen) += lookAhead;
2509 + inSize -= lookAhead;
2510 + p->tempBufSize = 0;
2514 + *status = LZMA_STATUS_FINISHED_WITH_MARK;
2515 + return (p->code == 0) ? SZ_OK : SZ_ERROR_DATA;
2518 +SRes LzmaDec_DecodeToBuf(CLzmaDec *p, Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen, ELzmaFinishMode finishMode, ELzmaStatus *status)
2520 + SizeT outSize = *destLen;
2521 + SizeT inSize = *srcLen;
2522 + *srcLen = *destLen = 0;
2525 + SizeT inSizeCur = inSize, outSizeCur, dicPos;
2526 + ELzmaFinishMode curFinishMode;
2528 + if (p->dicPos == p->dicBufSize)
2530 + dicPos = p->dicPos;
2531 + if (outSize > p->dicBufSize - dicPos)
2533 + outSizeCur = p->dicBufSize;
2534 + curFinishMode = LZMA_FINISH_ANY;
2538 + outSizeCur = dicPos + outSize;
2539 + curFinishMode = finishMode;
2542 + res = LzmaDec_DecodeToDic(p, outSizeCur, src, &inSizeCur, curFinishMode, status);
2544 + inSize -= inSizeCur;
2545 + *srcLen += inSizeCur;
2546 + outSizeCur = p->dicPos - dicPos;
2547 + memcpy(dest, p->dic + dicPos, outSizeCur);
2548 + dest += outSizeCur;
2549 + outSize -= outSizeCur;
2550 + *destLen += outSizeCur;
2553 + if (outSizeCur == 0 || outSize == 0)
2558 +void LzmaDec_FreeProbs(CLzmaDec *p, ISzAlloc *alloc)
2560 + alloc->Free(alloc, p->probs);
2564 +static void LzmaDec_FreeDict(CLzmaDec *p, ISzAlloc *alloc)
2566 + alloc->Free(alloc, p->dic);
2570 +void LzmaDec_Free(CLzmaDec *p, ISzAlloc *alloc)
2572 + LzmaDec_FreeProbs(p, alloc);
2573 + LzmaDec_FreeDict(p, alloc);
2576 +SRes LzmaProps_Decode(CLzmaProps *p, const Byte *data, unsigned size)
2581 + if (size < LZMA_PROPS_SIZE)
2582 + return SZ_ERROR_UNSUPPORTED;
2584 + dicSize = data[1] | ((UInt32)data[2] << 8) | ((UInt32)data[3] << 16) | ((UInt32)data[4] << 24);
2586 + if (dicSize < LZMA_DIC_MIN)
2587 + dicSize = LZMA_DIC_MIN;
2588 + p->dicSize = dicSize;
2591 + if (d >= (9 * 5 * 5))
2592 + return SZ_ERROR_UNSUPPORTED;
2602 +static SRes LzmaDec_AllocateProbs2(CLzmaDec *p, const CLzmaProps *propNew, ISzAlloc *alloc)
2604 + UInt32 numProbs = LzmaProps_GetNumProbs(propNew);
2605 + if (p->probs == 0 || numProbs != p->numProbs)
2607 + LzmaDec_FreeProbs(p, alloc);
2608 + p->probs = (CLzmaProb *)alloc->Alloc(alloc, numProbs * sizeof(CLzmaProb));
2609 + p->numProbs = numProbs;
2610 + if (p->probs == 0)
2611 + return SZ_ERROR_MEM;
2616 +SRes LzmaDec_AllocateProbs(CLzmaDec *p, const Byte *props, unsigned propsSize, ISzAlloc *alloc)
2618 + CLzmaProps propNew;
2619 + RINOK(LzmaProps_Decode(&propNew, props, propsSize));
2620 + RINOK(LzmaDec_AllocateProbs2(p, &propNew, alloc));
2621 + p->prop = propNew;
2625 +SRes LzmaDec_Allocate(CLzmaDec *p, const Byte *props, unsigned propsSize, ISzAlloc *alloc)
2627 + CLzmaProps propNew;
2629 + RINOK(LzmaProps_Decode(&propNew, props, propsSize));
2630 + RINOK(LzmaDec_AllocateProbs2(p, &propNew, alloc));
2631 + dicBufSize = propNew.dicSize;
2632 + if (p->dic == 0 || dicBufSize != p->dicBufSize)
2634 + LzmaDec_FreeDict(p, alloc);
2635 + p->dic = (Byte *)alloc->Alloc(alloc, dicBufSize);
2638 + LzmaDec_FreeProbs(p, alloc);
2639 + return SZ_ERROR_MEM;
2642 + p->dicBufSize = dicBufSize;
2643 + p->prop = propNew;
2647 +SRes LzmaDecode(Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen,
2648 + const Byte *propData, unsigned propSize, ELzmaFinishMode finishMode,
2649 + ELzmaStatus *status, ISzAlloc *alloc)
2653 + SizeT inSize = *srcLen;
2654 + SizeT outSize = *destLen;
2655 + *srcLen = *destLen = 0;
2656 + if (inSize < RC_INIT_SIZE)
2657 + return SZ_ERROR_INPUT_EOF;
2659 + LzmaDec_Construct(&p);
2660 + res = LzmaDec_AllocateProbs(&p, propData, propSize, alloc);
2664 + p.dicBufSize = outSize;
2669 + res = LzmaDec_DecodeToDic(&p, outSize, src, srcLen, finishMode, status);
2671 + if (res == SZ_OK && *status == LZMA_STATUS_NEEDS_MORE_INPUT)
2672 + res = SZ_ERROR_INPUT_EOF;
2674 + (*destLen) = p.dicPos;
2675 + LzmaDec_FreeProbs(&p, alloc);
2679 +++ b/jffsX-utils/lzma/LzmaEnc.c
2681 +/* LzmaEnc.c -- LZMA Encoder
2683 +Copyright (c) 1999-2008 Igor Pavlov
2684 +Read LzmaEnc.h for license options */
2686 +#if defined(SHOW_STAT) || defined(SHOW_STAT2)
2690 +#include <string.h>
2692 +#include "LzmaEnc.h"
2694 +#include "LzFind.h"
2695 +#ifdef COMPRESS_MF_MT
2696 +#include "LzFindMt.h"
2699 +/* #define SHOW_STAT */
2700 +/* #define SHOW_STAT2 */
2703 +static int ttt = 0;
2706 +#define kBlockSizeMax ((1 << LZMA_NUM_BLOCK_SIZE_BITS) - 1)
2708 +#define kBlockSize (9 << 10)
2709 +#define kUnpackBlockSize (1 << 18)
2710 +#define kMatchArraySize (1 << 21)
2711 +#define kMatchRecordMaxSize ((LZMA_MATCH_LEN_MAX * 2 + 3) * LZMA_MATCH_LEN_MAX)
2713 +#define kNumMaxDirectBits (31)
2715 +#define kNumTopBits 24
2716 +#define kTopValue ((UInt32)1 << kNumTopBits)
2718 +#define kNumBitModelTotalBits 11
2719 +#define kBitModelTotal (1 << kNumBitModelTotalBits)
2720 +#define kNumMoveBits 5
2721 +#define kProbInitValue (kBitModelTotal >> 1)
2723 +#define kNumMoveReducingBits 4
2724 +#define kNumBitPriceShiftBits 4
2725 +#define kBitPrice (1 << kNumBitPriceShiftBits)
2727 +void LzmaEncProps_Init(CLzmaEncProps *p)
2730 + p->dictSize = p->mc = 0;
2731 + p->lc = p->lp = p->pb = p->algo = p->fb = p->btMode = p->numHashBytes = p->numThreads = -1;
2732 + p->writeEndMark = 0;
2735 +void LzmaEncProps_Normalize(CLzmaEncProps *p)
2737 + int level = p->level;
2738 + if (level < 0) level = 5;
2740 + if (p->dictSize == 0) p->dictSize = (level <= 5 ? (1 << (level * 2 + 14)) : (level == 6 ? (1 << 25) : (1 << 26)));
2741 + if (p->lc < 0) p->lc = 3;
2742 + if (p->lp < 0) p->lp = 0;
2743 + if (p->pb < 0) p->pb = 2;
2744 + if (p->algo < 0) p->algo = (level < 5 ? 0 : 1);
2745 + if (p->fb < 0) p->fb = (level < 7 ? 32 : 64);
2746 + if (p->btMode < 0) p->btMode = (p->algo == 0 ? 0 : 1);
2747 + if (p->numHashBytes < 0) p->numHashBytes = 4;
2748 + if (p->mc == 0) p->mc = (16 + (p->fb >> 1)) >> (p->btMode ? 0 : 1);
2749 + if (p->numThreads < 0) p->numThreads = ((p->btMode && p->algo) ? 2 : 1);
2752 +UInt32 LzmaEncProps_GetDictSize(const CLzmaEncProps *props2)
2754 + CLzmaEncProps props = *props2;
2755 + LzmaEncProps_Normalize(&props);
2756 + return props.dictSize;
2759 +/* #define LZMA_LOG_BSR */
2760 +/* Define it for Intel's CPU */
2763 +#ifdef LZMA_LOG_BSR
2765 +#define kDicLogSizeMaxCompress 30
2767 +#define BSR2_RET(pos, res) { unsigned long i; _BitScanReverse(&i, (pos)); res = (i + i) + ((pos >> (i - 1)) & 1); }
2769 +UInt32 GetPosSlot1(UInt32 pos)
2772 + BSR2_RET(pos, res);
2775 +#define GetPosSlot2(pos, res) { BSR2_RET(pos, res); }
2776 +#define GetPosSlot(pos, res) { if (pos < 2) res = pos; else BSR2_RET(pos, res); }
2780 +#define kNumLogBits (9 + (int)sizeof(size_t) / 2)
2781 +#define kDicLogSizeMaxCompress ((kNumLogBits - 1) * 2 + 7)
2783 +static void LzmaEnc_FastPosInit(Byte *g_FastPos)
2785 + int c = 2, slotFast;
2789 + for (slotFast = 2; slotFast < kNumLogBits * 2; slotFast++)
2791 + UInt32 k = (1 << ((slotFast >> 1) - 1));
2793 + for (j = 0; j < k; j++, c++)
2794 + g_FastPos[c] = (Byte)slotFast;
2798 +#define BSR2_RET(pos, res) { UInt32 i = 6 + ((kNumLogBits - 1) & \
2799 + (0 - (((((UInt32)1 << (kNumLogBits + 6)) - 1) - pos) >> 31))); \
2800 + res = p->g_FastPos[pos >> i] + (i * 2); }
2802 +#define BSR2_RET(pos, res) { res = (pos < (1 << (kNumLogBits + 6))) ? \
2803 + p->g_FastPos[pos >> 6] + 12 : \
2804 + p->g_FastPos[pos >> (6 + kNumLogBits - 1)] + (6 + (kNumLogBits - 1)) * 2; }
2807 +#define GetPosSlot1(pos) p->g_FastPos[pos]
2808 +#define GetPosSlot2(pos, res) { BSR2_RET(pos, res); }
2809 +#define GetPosSlot(pos, res) { if (pos < kNumFullDistances) res = p->g_FastPos[pos]; else BSR2_RET(pos, res); }
2814 +#define LZMA_NUM_REPS 4
2816 +typedef unsigned CState;
2818 +typedef struct _COptimal
2831 + UInt32 backs[LZMA_NUM_REPS];
2834 +#define kNumOpts (1 << 12)
2836 +#define kNumLenToPosStates 4
2837 +#define kNumPosSlotBits 6
2838 +#define kDicLogSizeMin 0
2839 +#define kDicLogSizeMax 32
2840 +#define kDistTableSizeMax (kDicLogSizeMax * 2)
2843 +#define kNumAlignBits 4
2844 +#define kAlignTableSize (1 << kNumAlignBits)
2845 +#define kAlignMask (kAlignTableSize - 1)
2847 +#define kStartPosModelIndex 4
2848 +#define kEndPosModelIndex 14
2849 +#define kNumPosModels (kEndPosModelIndex - kStartPosModelIndex)
2851 +#define kNumFullDistances (1 << (kEndPosModelIndex / 2))
2853 +#ifdef _LZMA_PROB32
2854 +#define CLzmaProb UInt32
2856 +#define CLzmaProb UInt16
2859 +#define LZMA_PB_MAX 4
2860 +#define LZMA_LC_MAX 8
2861 +#define LZMA_LP_MAX 4
2863 +#define LZMA_NUM_PB_STATES_MAX (1 << LZMA_PB_MAX)
2866 +#define kLenNumLowBits 3
2867 +#define kLenNumLowSymbols (1 << kLenNumLowBits)
2868 +#define kLenNumMidBits 3
2869 +#define kLenNumMidSymbols (1 << kLenNumMidBits)
2870 +#define kLenNumHighBits 8
2871 +#define kLenNumHighSymbols (1 << kLenNumHighBits)
2873 +#define kLenNumSymbolsTotal (kLenNumLowSymbols + kLenNumMidSymbols + kLenNumHighSymbols)
2875 +#define LZMA_MATCH_LEN_MIN 2
2876 +#define LZMA_MATCH_LEN_MAX (LZMA_MATCH_LEN_MIN + kLenNumSymbolsTotal - 1)
2878 +#define kNumStates 12
2883 + CLzmaProb choice2;
2884 + CLzmaProb low[LZMA_NUM_PB_STATES_MAX << kLenNumLowBits];
2885 + CLzmaProb mid[LZMA_NUM_PB_STATES_MAX << kLenNumMidBits];
2886 + CLzmaProb high[kLenNumHighSymbols];
2892 + UInt32 prices[LZMA_NUM_PB_STATES_MAX][kLenNumSymbolsTotal];
2894 + UInt32 counters[LZMA_NUM_PB_STATES_MAX];
2897 +typedef struct _CRangeEnc
2906 + ISeqOutStream *outStream;
2911 +typedef struct _CSeqInStreamBuf
2913 + ISeqInStream funcTable;
2918 +static SRes MyRead(void *pp, void *data, size_t *size)
2920 + size_t curSize = *size;
2921 + CSeqInStreamBuf *p = (CSeqInStreamBuf *)pp;
2922 + if (p->rem < curSize)
2924 + memcpy(data, p->data, curSize);
2925 + p->rem -= curSize;
2926 + p->data += curSize;
2933 + CLzmaProb *litProbs;
2935 + CLzmaProb isMatch[kNumStates][LZMA_NUM_PB_STATES_MAX];
2936 + CLzmaProb isRep[kNumStates];
2937 + CLzmaProb isRepG0[kNumStates];
2938 + CLzmaProb isRepG1[kNumStates];
2939 + CLzmaProb isRepG2[kNumStates];
2940 + CLzmaProb isRep0Long[kNumStates][LZMA_NUM_PB_STATES_MAX];
2942 + CLzmaProb posSlotEncoder[kNumLenToPosStates][1 << kNumPosSlotBits];
2943 + CLzmaProb posEncoders[kNumFullDistances - kEndPosModelIndex];
2944 + CLzmaProb posAlignEncoder[1 << kNumAlignBits];
2946 + CLenPriceEnc lenEnc;
2947 + CLenPriceEnc repLenEnc;
2949 + UInt32 reps[LZMA_NUM_REPS];
2953 +typedef struct _CLzmaEnc
2955 + IMatchFinder matchFinder;
2956 + void *matchFinderObj;
2958 + #ifdef COMPRESS_MF_MT
2960 + CMatchFinderMt matchFinderMt;
2963 + CMatchFinder matchFinderBase;
2965 + #ifdef COMPRESS_MF_MT
2969 + UInt32 optimumEndIndex;
2970 + UInt32 optimumCurrentIndex;
2972 + Bool longestMatchWasFound;
2973 + UInt32 longestMatchLength;
2974 + UInt32 numDistancePairs;
2976 + COptimal opt[kNumOpts];
2978 + #ifndef LZMA_LOG_BSR
2979 + Byte g_FastPos[1 << kNumLogBits];
2982 + UInt32 ProbPrices[kBitModelTotal >> kNumMoveReducingBits];
2983 + UInt32 matchDistances[LZMA_MATCH_LEN_MAX * 2 + 2 + 1];
2984 + UInt32 numFastBytes;
2985 + UInt32 additionalOffset;
2986 + UInt32 reps[LZMA_NUM_REPS];
2989 + UInt32 posSlotPrices[kNumLenToPosStates][kDistTableSizeMax];
2990 + UInt32 distancesPrices[kNumLenToPosStates][kNumFullDistances];
2991 + UInt32 alignPrices[kAlignTableSize];
2992 + UInt32 alignPriceCount;
2994 + UInt32 distTableSize;
2996 + unsigned lc, lp, pb;
2997 + unsigned lpMask, pbMask;
2999 + CLzmaProb *litProbs;
3001 + CLzmaProb isMatch[kNumStates][LZMA_NUM_PB_STATES_MAX];
3002 + CLzmaProb isRep[kNumStates];
3003 + CLzmaProb isRepG0[kNumStates];
3004 + CLzmaProb isRepG1[kNumStates];
3005 + CLzmaProb isRepG2[kNumStates];
3006 + CLzmaProb isRep0Long[kNumStates][LZMA_NUM_PB_STATES_MAX];
3008 + CLzmaProb posSlotEncoder[kNumLenToPosStates][1 << kNumPosSlotBits];
3009 + CLzmaProb posEncoders[kNumFullDistances - kEndPosModelIndex];
3010 + CLzmaProb posAlignEncoder[1 << kNumAlignBits];
3012 + CLenPriceEnc lenEnc;
3013 + CLenPriceEnc repLenEnc;
3021 + Bool writeEndMark;
3023 + UInt32 matchPriceCount;
3029 + UInt32 matchFinderCycles;
3031 + ISeqInStream *inStream;
3032 + CSeqInStreamBuf seqBufInStream;
3034 + CSaveState saveState;
3037 +static void LzmaEnc_SaveState(CLzmaEncHandle pp)
3039 + CLzmaEnc *p = (CLzmaEnc *)pp;
3040 + CSaveState *dest = &p->saveState;
3042 + dest->lenEnc = p->lenEnc;
3043 + dest->repLenEnc = p->repLenEnc;
3044 + dest->state = p->state;
3046 + for (i = 0; i < kNumStates; i++)
3048 + memcpy(dest->isMatch[i], p->isMatch[i], sizeof(p->isMatch[i]));
3049 + memcpy(dest->isRep0Long[i], p->isRep0Long[i], sizeof(p->isRep0Long[i]));
3051 + for (i = 0; i < kNumLenToPosStates; i++)
3052 + memcpy(dest->posSlotEncoder[i], p->posSlotEncoder[i], sizeof(p->posSlotEncoder[i]));
3053 + memcpy(dest->isRep, p->isRep, sizeof(p->isRep));
3054 + memcpy(dest->isRepG0, p->isRepG0, sizeof(p->isRepG0));
3055 + memcpy(dest->isRepG1, p->isRepG1, sizeof(p->isRepG1));
3056 + memcpy(dest->isRepG2, p->isRepG2, sizeof(p->isRepG2));
3057 + memcpy(dest->posEncoders, p->posEncoders, sizeof(p->posEncoders));
3058 + memcpy(dest->posAlignEncoder, p->posAlignEncoder, sizeof(p->posAlignEncoder));
3059 + memcpy(dest->reps, p->reps, sizeof(p->reps));
3060 + memcpy(dest->litProbs, p->litProbs, (0x300 << p->lclp) * sizeof(CLzmaProb));
3063 +static void LzmaEnc_RestoreState(CLzmaEncHandle pp)
3065 + CLzmaEnc *dest = (CLzmaEnc *)pp;
3066 + const CSaveState *p = &dest->saveState;
3068 + dest->lenEnc = p->lenEnc;
3069 + dest->repLenEnc = p->repLenEnc;
3070 + dest->state = p->state;
3072 + for (i = 0; i < kNumStates; i++)
3074 + memcpy(dest->isMatch[i], p->isMatch[i], sizeof(p->isMatch[i]));
3075 + memcpy(dest->isRep0Long[i], p->isRep0Long[i], sizeof(p->isRep0Long[i]));
3077 + for (i = 0; i < kNumLenToPosStates; i++)
3078 + memcpy(dest->posSlotEncoder[i], p->posSlotEncoder[i], sizeof(p->posSlotEncoder[i]));
3079 + memcpy(dest->isRep, p->isRep, sizeof(p->isRep));
3080 + memcpy(dest->isRepG0, p->isRepG0, sizeof(p->isRepG0));
3081 + memcpy(dest->isRepG1, p->isRepG1, sizeof(p->isRepG1));
3082 + memcpy(dest->isRepG2, p->isRepG2, sizeof(p->isRepG2));
3083 + memcpy(dest->posEncoders, p->posEncoders, sizeof(p->posEncoders));
3084 + memcpy(dest->posAlignEncoder, p->posAlignEncoder, sizeof(p->posAlignEncoder));
3085 + memcpy(dest->reps, p->reps, sizeof(p->reps));
3086 + memcpy(dest->litProbs, p->litProbs, (0x300 << dest->lclp) * sizeof(CLzmaProb));
3089 +SRes LzmaEnc_SetProps(CLzmaEncHandle pp, const CLzmaEncProps *props2)
3091 + CLzmaEnc *p = (CLzmaEnc *)pp;
3092 + CLzmaEncProps props = *props2;
3093 + LzmaEncProps_Normalize(&props);
3095 + if (props.lc > LZMA_LC_MAX || props.lp > LZMA_LP_MAX || props.pb > LZMA_PB_MAX ||
3096 + props.dictSize > (1 << kDicLogSizeMaxCompress) || props.dictSize > (1 << 30))
3097 + return SZ_ERROR_PARAM;
3098 + p->dictSize = props.dictSize;
3099 + p->matchFinderCycles = props.mc;
3101 + unsigned fb = props.fb;
3104 + if (fb > LZMA_MATCH_LEN_MAX)
3105 + fb = LZMA_MATCH_LEN_MAX;
3106 + p->numFastBytes = fb;
3111 + p->fastMode = (props.algo == 0);
3112 + p->matchFinderBase.btMode = props.btMode;
3114 + UInt32 numHashBytes = 4;
3117 + if (props.numHashBytes < 2)
3119 + else if (props.numHashBytes < 4)
3120 + numHashBytes = props.numHashBytes;
3122 + p->matchFinderBase.numHashBytes = numHashBytes;
3125 + p->matchFinderBase.cutValue = props.mc;
3127 + p->writeEndMark = props.writeEndMark;
3129 + #ifdef COMPRESS_MF_MT
3131 + if (newMultiThread != _multiThread)
3133 + ReleaseMatchFinder();
3134 + _multiThread = newMultiThread;
3137 + p->multiThread = (props.numThreads > 1);
3143 +static const int kLiteralNextStates[kNumStates] = {0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 4, 5};
3144 +static const int kMatchNextStates[kNumStates] = {7, 7, 7, 7, 7, 7, 7, 10, 10, 10, 10, 10};
3145 +static const int kRepNextStates[kNumStates] = {8, 8, 8, 8, 8, 8, 8, 11, 11, 11, 11, 11};
3146 +static const int kShortRepNextStates[kNumStates]= {9, 9, 9, 9, 9, 9, 9, 11, 11, 11, 11, 11};
3149 + void UpdateChar() { Index = kLiteralNextStates[Index]; }
3150 + void UpdateMatch() { Index = kMatchNextStates[Index]; }
3151 + void UpdateRep() { Index = kRepNextStates[Index]; }
3152 + void UpdateShortRep() { Index = kShortRepNextStates[Index]; }
3155 +#define IsCharState(s) ((s) < 7)
3158 +#define GetLenToPosState(len) (((len) < kNumLenToPosStates + 1) ? (len) - 2 : kNumLenToPosStates - 1)
3160 +#define kInfinityPrice (1 << 30)
3162 +static void RangeEnc_Construct(CRangeEnc *p)
3168 +#define RangeEnc_GetProcessed(p) ((p)->processed + ((p)->buf - (p)->bufBase) + (p)->cacheSize)
3170 +#define RC_BUF_SIZE (1 << 16)
3171 +static int RangeEnc_Alloc(CRangeEnc *p, ISzAlloc *alloc)
3173 + if (p->bufBase == 0)
3175 + p->bufBase = (Byte *)alloc->Alloc(alloc, RC_BUF_SIZE);
3176 + if (p->bufBase == 0)
3178 + p->bufLim = p->bufBase + RC_BUF_SIZE;
3183 +static void RangeEnc_Free(CRangeEnc *p, ISzAlloc *alloc)
3185 + alloc->Free(alloc, p->bufBase);
3189 +static void RangeEnc_Init(CRangeEnc *p)
3191 + /* Stream.Init(); */
3193 + p->range = 0xFFFFFFFF;
3197 + p->buf = p->bufBase;
3203 +static void RangeEnc_FlushStream(CRangeEnc *p)
3206 + if (p->res != SZ_OK)
3208 + num = p->buf - p->bufBase;
3209 + if (num != p->outStream->Write(p->outStream, p->bufBase, num))
3210 + p->res = SZ_ERROR_WRITE;
3211 + p->processed += num;
3212 + p->buf = p->bufBase;
3215 +static void MY_FAST_CALL RangeEnc_ShiftLow(CRangeEnc *p)
3217 + if ((UInt32)p->low < (UInt32)0xFF000000 || (int)(p->low >> 32) != 0)
3219 + Byte temp = p->cache;
3222 + Byte *buf = p->buf;
3223 + *buf++ = (Byte)(temp + (Byte)(p->low >> 32));
3225 + if (buf == p->bufLim)
3226 + RangeEnc_FlushStream(p);
3229 + while (--p->cacheSize != 0);
3230 + p->cache = (Byte)((UInt32)p->low >> 24);
3233 + p->low = (UInt32)p->low << 8;
3236 +static void RangeEnc_FlushData(CRangeEnc *p)
3239 + for (i = 0; i < 5; i++)
3240 + RangeEnc_ShiftLow(p);
3243 +static void RangeEnc_EncodeDirectBits(CRangeEnc *p, UInt32 value, int numBits)
3248 + p->low += p->range & (0 - ((value >> --numBits) & 1));
3249 + if (p->range < kTopValue)
3252 + RangeEnc_ShiftLow(p);
3255 + while (numBits != 0);
3258 +static void RangeEnc_EncodeBit(CRangeEnc *p, CLzmaProb *prob, UInt32 symbol)
3260 + UInt32 ttt = *prob;
3261 + UInt32 newBound = (p->range >> kNumBitModelTotalBits) * ttt;
3264 + p->range = newBound;
3265 + ttt += (kBitModelTotal - ttt) >> kNumMoveBits;
3269 + p->low += newBound;
3270 + p->range -= newBound;
3271 + ttt -= ttt >> kNumMoveBits;
3273 + *prob = (CLzmaProb)ttt;
3274 + if (p->range < kTopValue)
3277 + RangeEnc_ShiftLow(p);
3281 +static void LitEnc_Encode(CRangeEnc *p, CLzmaProb *probs, UInt32 symbol)
3286 + RangeEnc_EncodeBit(p, probs + (symbol >> 8), (symbol >> 7) & 1);
3289 + while (symbol < 0x10000);
3292 +static void LitEnc_EncodeMatched(CRangeEnc *p, CLzmaProb *probs, UInt32 symbol, UInt32 matchByte)
3294 + UInt32 offs = 0x100;
3299 + RangeEnc_EncodeBit(p, probs + (offs + (matchByte & offs) + (symbol >> 8)), (symbol >> 7) & 1);
3301 + offs &= ~(matchByte ^ symbol);
3303 + while (symbol < 0x10000);
3306 +static void LzmaEnc_InitPriceTables(UInt32 *ProbPrices)
3309 + for (i = (1 << kNumMoveReducingBits) / 2; i < kBitModelTotal; i += (1 << kNumMoveReducingBits))
3311 + const int kCyclesBits = kNumBitPriceShiftBits;
3313 + UInt32 bitCount = 0;
3315 + for (j = 0; j < kCyclesBits; j++)
3319 + while (w >= ((UInt32)1 << 16))
3325 + ProbPrices[i >> kNumMoveReducingBits] = ((kNumBitModelTotalBits << kCyclesBits) - 15 - bitCount);
3330 +#define GET_PRICE(prob, symbol) \
3331 + p->ProbPrices[((prob) ^ (((-(int)(symbol))) & (kBitModelTotal - 1))) >> kNumMoveReducingBits];
3333 +#define GET_PRICEa(prob, symbol) \
3334 + ProbPrices[((prob) ^ ((-((int)(symbol))) & (kBitModelTotal - 1))) >> kNumMoveReducingBits];
3336 +#define GET_PRICE_0(prob) p->ProbPrices[(prob) >> kNumMoveReducingBits]
3337 +#define GET_PRICE_1(prob) p->ProbPrices[((prob) ^ (kBitModelTotal - 1)) >> kNumMoveReducingBits]
3339 +#define GET_PRICE_0a(prob) ProbPrices[(prob) >> kNumMoveReducingBits]
3340 +#define GET_PRICE_1a(prob) ProbPrices[((prob) ^ (kBitModelTotal - 1)) >> kNumMoveReducingBits]
3342 +static UInt32 LitEnc_GetPrice(const CLzmaProb *probs, UInt32 symbol, UInt32 *ProbPrices)
3348 + price += GET_PRICEa(probs[symbol >> 8], (symbol >> 7) & 1);
3351 + while (symbol < 0x10000);
3355 +static UInt32 LitEnc_GetPriceMatched(const CLzmaProb *probs, UInt32 symbol, UInt32 matchByte, UInt32 *ProbPrices)
3358 + UInt32 offs = 0x100;
3363 + price += GET_PRICEa(probs[offs + (matchByte & offs) + (symbol >> 8)], (symbol >> 7) & 1);
3365 + offs &= ~(matchByte ^ symbol);
3367 + while (symbol < 0x10000);
3372 +static void RcTree_Encode(CRangeEnc *rc, CLzmaProb *probs, int numBitLevels, UInt32 symbol)
3376 + for (i = numBitLevels; i != 0 ;)
3380 + bit = (symbol >> i) & 1;
3381 + RangeEnc_EncodeBit(rc, probs + m, bit);
3382 + m = (m << 1) | bit;
3386 +static void RcTree_ReverseEncode(CRangeEnc *rc, CLzmaProb *probs, int numBitLevels, UInt32 symbol)
3390 + for (i = 0; i < numBitLevels; i++)
3392 + UInt32 bit = symbol & 1;
3393 + RangeEnc_EncodeBit(rc, probs + m, bit);
3394 + m = (m << 1) | bit;
3399 +static UInt32 RcTree_GetPrice(const CLzmaProb *probs, int numBitLevels, UInt32 symbol, UInt32 *ProbPrices)
3402 + symbol |= (1 << numBitLevels);
3403 + while (symbol != 1)
3405 + price += GET_PRICEa(probs[symbol >> 1], symbol & 1);
3411 +static UInt32 RcTree_ReverseGetPrice(const CLzmaProb *probs, int numBitLevels, UInt32 symbol, UInt32 *ProbPrices)
3416 + for (i = numBitLevels; i != 0; i--)
3418 + UInt32 bit = symbol & 1;
3420 + price += GET_PRICEa(probs[m], bit);
3421 + m = (m << 1) | bit;
3427 +static void LenEnc_Init(CLenEnc *p)
3430 + p->choice = p->choice2 = kProbInitValue;
3431 + for (i = 0; i < (LZMA_NUM_PB_STATES_MAX << kLenNumLowBits); i++)
3432 + p->low[i] = kProbInitValue;
3433 + for (i = 0; i < (LZMA_NUM_PB_STATES_MAX << kLenNumMidBits); i++)
3434 + p->mid[i] = kProbInitValue;
3435 + for (i = 0; i < kLenNumHighSymbols; i++)
3436 + p->high[i] = kProbInitValue;
3439 +static void LenEnc_Encode(CLenEnc *p, CRangeEnc *rc, UInt32 symbol, UInt32 posState)
3441 + if (symbol < kLenNumLowSymbols)
3443 + RangeEnc_EncodeBit(rc, &p->choice, 0);
3444 + RcTree_Encode(rc, p->low + (posState << kLenNumLowBits), kLenNumLowBits, symbol);
3448 + RangeEnc_EncodeBit(rc, &p->choice, 1);
3449 + if (symbol < kLenNumLowSymbols + kLenNumMidSymbols)
3451 + RangeEnc_EncodeBit(rc, &p->choice2, 0);
3452 + RcTree_Encode(rc, p->mid + (posState << kLenNumMidBits), kLenNumMidBits, symbol - kLenNumLowSymbols);
3456 + RangeEnc_EncodeBit(rc, &p->choice2, 1);
3457 + RcTree_Encode(rc, p->high, kLenNumHighBits, symbol - kLenNumLowSymbols - kLenNumMidSymbols);
3462 +static void LenEnc_SetPrices(CLenEnc *p, UInt32 posState, UInt32 numSymbols, UInt32 *prices, UInt32 *ProbPrices)
3464 + UInt32 a0 = GET_PRICE_0a(p->choice);
3465 + UInt32 a1 = GET_PRICE_1a(p->choice);
3466 + UInt32 b0 = a1 + GET_PRICE_0a(p->choice2);
3467 + UInt32 b1 = a1 + GET_PRICE_1a(p->choice2);
3469 + for (i = 0; i < kLenNumLowSymbols; i++)
3471 + if (i >= numSymbols)
3473 + prices[i] = a0 + RcTree_GetPrice(p->low + (posState << kLenNumLowBits), kLenNumLowBits, i, ProbPrices);
3475 + for (; i < kLenNumLowSymbols + kLenNumMidSymbols; i++)
3477 + if (i >= numSymbols)
3479 + prices[i] = b0 + RcTree_GetPrice(p->mid + (posState << kLenNumMidBits), kLenNumMidBits, i - kLenNumLowSymbols, ProbPrices);
3481 + for (; i < numSymbols; i++)
3482 + prices[i] = b1 + RcTree_GetPrice(p->high, kLenNumHighBits, i - kLenNumLowSymbols - kLenNumMidSymbols, ProbPrices);
3485 +static void MY_FAST_CALL LenPriceEnc_UpdateTable(CLenPriceEnc *p, UInt32 posState, UInt32 *ProbPrices)
3487 + LenEnc_SetPrices(&p->p, posState, p->tableSize, p->prices[posState], ProbPrices);
3488 + p->counters[posState] = p->tableSize;
3491 +static void LenPriceEnc_UpdateTables(CLenPriceEnc *p, UInt32 numPosStates, UInt32 *ProbPrices)
3494 + for (posState = 0; posState < numPosStates; posState++)
3495 + LenPriceEnc_UpdateTable(p, posState, ProbPrices);
3498 +static void LenEnc_Encode2(CLenPriceEnc *p, CRangeEnc *rc, UInt32 symbol, UInt32 posState, Bool updatePrice, UInt32 *ProbPrices)
3500 + LenEnc_Encode(&p->p, rc, symbol, posState);
3502 + if (--p->counters[posState] == 0)
3503 + LenPriceEnc_UpdateTable(p, posState, ProbPrices);
3509 +static void MovePos(CLzmaEnc *p, UInt32 num)
3513 + printf("\n MovePos %d", num);
3517 + p->additionalOffset += num;
3518 + p->matchFinder.Skip(p->matchFinderObj, num);
3522 +static UInt32 ReadMatchDistances(CLzmaEnc *p, UInt32 *numDistancePairsRes)
3524 + UInt32 lenRes = 0, numDistancePairs;
3525 + numDistancePairs = p->matchFinder.GetMatches(p->matchFinderObj, p->matchDistances);
3527 + printf("\n i = %d numPairs = %d ", ttt, numDistancePairs / 2);
3534 + for (i = 0; i < numDistancePairs; i += 2)
3535 + printf("%2d %6d | ", p->matchDistances[i], p->matchDistances[i + 1]);
3538 + if (numDistancePairs > 0)
3540 + lenRes = p->matchDistances[numDistancePairs - 2];
3541 + if (lenRes == p->numFastBytes)
3543 + UInt32 numAvail = p->matchFinder.GetNumAvailableBytes(p->matchFinderObj) + 1;
3544 + const Byte *pby = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - 1;
3545 + UInt32 distance = p->matchDistances[numDistancePairs - 1] + 1;
3546 + if (numAvail > LZMA_MATCH_LEN_MAX)
3547 + numAvail = LZMA_MATCH_LEN_MAX;
3550 + const Byte *pby2 = pby - distance;
3551 + for (; lenRes < numAvail && pby[lenRes] == pby2[lenRes]; lenRes++);
3555 + p->additionalOffset++;
3556 + *numDistancePairsRes = numDistancePairs;
3561 +#define MakeAsChar(p) (p)->backPrev = (UInt32)(-1); (p)->prev1IsChar = False;
3562 +#define MakeAsShortRep(p) (p)->backPrev = 0; (p)->prev1IsChar = False;
3563 +#define IsShortRep(p) ((p)->backPrev == 0)
3565 +static UInt32 GetRepLen1Price(CLzmaEnc *p, UInt32 state, UInt32 posState)
3568 + GET_PRICE_0(p->isRepG0[state]) +
3569 + GET_PRICE_0(p->isRep0Long[state][posState]);
3572 +static UInt32 GetPureRepPrice(CLzmaEnc *p, UInt32 repIndex, UInt32 state, UInt32 posState)
3575 + if (repIndex == 0)
3577 + price = GET_PRICE_0(p->isRepG0[state]);
3578 + price += GET_PRICE_1(p->isRep0Long[state][posState]);
3582 + price = GET_PRICE_1(p->isRepG0[state]);
3583 + if (repIndex == 1)
3584 + price += GET_PRICE_0(p->isRepG1[state]);
3587 + price += GET_PRICE_1(p->isRepG1[state]);
3588 + price += GET_PRICE(p->isRepG2[state], repIndex - 2);
3594 +static UInt32 GetRepPrice(CLzmaEnc *p, UInt32 repIndex, UInt32 len, UInt32 state, UInt32 posState)
3596 + return p->repLenEnc.prices[posState][len - LZMA_MATCH_LEN_MIN] +
3597 + GetPureRepPrice(p, repIndex, state, posState);
3600 +static UInt32 Backward(CLzmaEnc *p, UInt32 *backRes, UInt32 cur)
3602 + UInt32 posMem = p->opt[cur].posPrev;
3603 + UInt32 backMem = p->opt[cur].backPrev;
3604 + p->optimumEndIndex = cur;
3607 + if (p->opt[cur].prev1IsChar)
3609 + MakeAsChar(&p->opt[posMem])
3610 + p->opt[posMem].posPrev = posMem - 1;
3611 + if (p->opt[cur].prev2)
3613 + p->opt[posMem - 1].prev1IsChar = False;
3614 + p->opt[posMem - 1].posPrev = p->opt[cur].posPrev2;
3615 + p->opt[posMem - 1].backPrev = p->opt[cur].backPrev2;
3619 + UInt32 posPrev = posMem;
3620 + UInt32 backCur = backMem;
3622 + backMem = p->opt[posPrev].backPrev;
3623 + posMem = p->opt[posPrev].posPrev;
3625 + p->opt[posPrev].backPrev = backCur;
3626 + p->opt[posPrev].posPrev = cur;
3631 + *backRes = p->opt[0].backPrev;
3632 + p->optimumCurrentIndex = p->opt[0].posPrev;
3633 + return p->optimumCurrentIndex;
3636 +#define LIT_PROBS(pos, prevByte) (p->litProbs + ((((pos) & p->lpMask) << p->lc) + ((prevByte) >> (8 - p->lc))) * 0x300)
3638 +static UInt32 GetOptimum(CLzmaEnc *p, UInt32 position, UInt32 *backRes)
3640 + UInt32 numAvailableBytes, lenMain, numDistancePairs;
3642 + UInt32 reps[LZMA_NUM_REPS];
3643 + UInt32 repLens[LZMA_NUM_REPS];
3644 + UInt32 repMaxIndex, i;
3645 + UInt32 *matchDistances;
3646 + Byte currentByte, matchByte;
3648 + UInt32 matchPrice, repMatchPrice;
3651 + UInt32 normalMatchPrice;
3653 + if (p->optimumEndIndex != p->optimumCurrentIndex)
3655 + const COptimal *opt = &p->opt[p->optimumCurrentIndex];
3656 + UInt32 lenRes = opt->posPrev - p->optimumCurrentIndex;
3657 + *backRes = opt->backPrev;
3658 + p->optimumCurrentIndex = opt->posPrev;
3661 + p->optimumCurrentIndex = p->optimumEndIndex = 0;
3663 + numAvailableBytes = p->matchFinder.GetNumAvailableBytes(p->matchFinderObj);
3665 + if (!p->longestMatchWasFound)
3667 + lenMain = ReadMatchDistances(p, &numDistancePairs);
3671 + lenMain = p->longestMatchLength;
3672 + numDistancePairs = p->numDistancePairs;
3673 + p->longestMatchWasFound = False;
3676 + data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - 1;
3677 + if (numAvailableBytes < 2)
3679 + *backRes = (UInt32)(-1);
3682 + if (numAvailableBytes > LZMA_MATCH_LEN_MAX)
3683 + numAvailableBytes = LZMA_MATCH_LEN_MAX;
3686 + for (i = 0; i < LZMA_NUM_REPS; i++)
3689 + const Byte *data2;
3690 + reps[i] = p->reps[i];
3691 + data2 = data - (reps[i] + 1);
3692 + if (data[0] != data2[0] || data[1] != data2[1])
3697 + for (lenTest = 2; lenTest < numAvailableBytes && data[lenTest] == data2[lenTest]; lenTest++);
3698 + repLens[i] = lenTest;
3699 + if (lenTest > repLens[repMaxIndex])
3702 + if (repLens[repMaxIndex] >= p->numFastBytes)
3705 + *backRes = repMaxIndex;
3706 + lenRes = repLens[repMaxIndex];
3707 + MovePos(p, lenRes - 1);
3711 + matchDistances = p->matchDistances;
3712 + if (lenMain >= p->numFastBytes)
3714 + *backRes = matchDistances[numDistancePairs - 1] + LZMA_NUM_REPS;
3715 + MovePos(p, lenMain - 1);
3718 + currentByte = *data;
3719 + matchByte = *(data - (reps[0] + 1));
3721 + if (lenMain < 2 && currentByte != matchByte && repLens[repMaxIndex] < 2)
3723 + *backRes = (UInt32)-1;
3727 + p->opt[0].state = (CState)p->state;
3729 + posState = (position & p->pbMask);
3732 + const CLzmaProb *probs = LIT_PROBS(position, *(data - 1));
3733 + p->opt[1].price = GET_PRICE_0(p->isMatch[p->state][posState]) +
3734 + (!IsCharState(p->state) ?
3735 + LitEnc_GetPriceMatched(probs, currentByte, matchByte, p->ProbPrices) :
3736 + LitEnc_GetPrice(probs, currentByte, p->ProbPrices));
3739 + MakeAsChar(&p->opt[1]);
3741 + matchPrice = GET_PRICE_1(p->isMatch[p->state][posState]);
3742 + repMatchPrice = matchPrice + GET_PRICE_1(p->isRep[p->state]);
3744 + if (matchByte == currentByte)
3746 + UInt32 shortRepPrice = repMatchPrice + GetRepLen1Price(p, p->state, posState);
3747 + if (shortRepPrice < p->opt[1].price)
3749 + p->opt[1].price = shortRepPrice;
3750 + MakeAsShortRep(&p->opt[1]);
3753 + lenEnd = ((lenMain >= repLens[repMaxIndex]) ? lenMain : repLens[repMaxIndex]);
3757 + *backRes = p->opt[1].backPrev;
3761 + p->opt[1].posPrev = 0;
3762 + for (i = 0; i < LZMA_NUM_REPS; i++)
3763 + p->opt[0].backs[i] = reps[i];
3767 + p->opt[len--].price = kInfinityPrice;
3770 + for (i = 0; i < LZMA_NUM_REPS; i++)
3772 + UInt32 repLen = repLens[i];
3776 + price = repMatchPrice + GetPureRepPrice(p, i, p->state, posState);
3779 + UInt32 curAndLenPrice = price + p->repLenEnc.prices[posState][repLen - 2];
3780 + COptimal *opt = &p->opt[repLen];
3781 + if (curAndLenPrice < opt->price)
3783 + opt->price = curAndLenPrice;
3785 + opt->backPrev = i;
3786 + opt->prev1IsChar = False;
3789 + while (--repLen >= 2);
3792 + normalMatchPrice = matchPrice + GET_PRICE_0(p->isRep[p->state]);
3794 + len = ((repLens[0] >= 2) ? repLens[0] + 1 : 2);
3795 + if (len <= lenMain)
3798 + while (len > matchDistances[offs])
3803 + UInt32 distance = matchDistances[offs + 1];
3805 + UInt32 curAndLenPrice = normalMatchPrice + p->lenEnc.prices[posState][len - LZMA_MATCH_LEN_MIN];
3806 + UInt32 lenToPosState = GetLenToPosState(len);
3807 + if (distance < kNumFullDistances)
3808 + curAndLenPrice += p->distancesPrices[lenToPosState][distance];
3812 + GetPosSlot2(distance, slot);
3813 + curAndLenPrice += p->alignPrices[distance & kAlignMask] + p->posSlotPrices[lenToPosState][slot];
3815 + opt = &p->opt[len];
3816 + if (curAndLenPrice < opt->price)
3818 + opt->price = curAndLenPrice;
3820 + opt->backPrev = distance + LZMA_NUM_REPS;
3821 + opt->prev1IsChar = False;
3823 + if (len == matchDistances[offs])
3826 + if (offs == numDistancePairs)
3835 + if (position >= 0)
3838 + printf("\n pos = %4X", position);
3839 + for (i = cur; i <= lenEnd; i++)
3840 + printf("\nprice[%4X] = %d", position - cur + i, p->opt[i].price);
3846 + UInt32 numAvailableBytesFull, newLen, numDistancePairs;
3853 + Byte currentByte, matchByte;
3855 + UInt32 curAnd1Price;
3856 + COptimal *nextOpt;
3857 + UInt32 matchPrice, repMatchPrice;
3858 + UInt32 numAvailableBytes;
3862 + if (cur == lenEnd)
3863 + return Backward(p, backRes, cur);
3865 + numAvailableBytesFull = p->matchFinder.GetNumAvailableBytes(p->matchFinderObj);
3866 + newLen = ReadMatchDistances(p, &numDistancePairs);
3867 + if (newLen >= p->numFastBytes)
3869 + p->numDistancePairs = numDistancePairs;
3870 + p->longestMatchLength = newLen;
3871 + p->longestMatchWasFound = True;
3872 + return Backward(p, backRes, cur);
3875 + curOpt = &p->opt[cur];
3876 + posPrev = curOpt->posPrev;
3877 + if (curOpt->prev1IsChar)
3880 + if (curOpt->prev2)
3882 + state = p->opt[curOpt->posPrev2].state;
3883 + if (curOpt->backPrev2 < LZMA_NUM_REPS)
3884 + state = kRepNextStates[state];
3886 + state = kMatchNextStates[state];
3889 + state = p->opt[posPrev].state;
3890 + state = kLiteralNextStates[state];
3893 + state = p->opt[posPrev].state;
3894 + if (posPrev == cur - 1)
3896 + if (IsShortRep(curOpt))
3897 + state = kShortRepNextStates[state];
3899 + state = kLiteralNextStates[state];
3904 + const COptimal *prevOpt;
3905 + if (curOpt->prev1IsChar && curOpt->prev2)
3907 + posPrev = curOpt->posPrev2;
3908 + pos = curOpt->backPrev2;
3909 + state = kRepNextStates[state];
3913 + pos = curOpt->backPrev;
3914 + if (pos < LZMA_NUM_REPS)
3915 + state = kRepNextStates[state];
3917 + state = kMatchNextStates[state];
3919 + prevOpt = &p->opt[posPrev];
3920 + if (pos < LZMA_NUM_REPS)
3923 + reps[0] = prevOpt->backs[pos];
3924 + for (i = 1; i <= pos; i++)
3925 + reps[i] = prevOpt->backs[i - 1];
3926 + for (; i < LZMA_NUM_REPS; i++)
3927 + reps[i] = prevOpt->backs[i];
3932 + reps[0] = (pos - LZMA_NUM_REPS);
3933 + for (i = 1; i < LZMA_NUM_REPS; i++)
3934 + reps[i] = prevOpt->backs[i - 1];
3937 + curOpt->state = (CState)state;
3939 + curOpt->backs[0] = reps[0];
3940 + curOpt->backs[1] = reps[1];
3941 + curOpt->backs[2] = reps[2];
3942 + curOpt->backs[3] = reps[3];
3944 + curPrice = curOpt->price;
3945 + nextIsChar = False;
3946 + data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - 1;
3947 + currentByte = *data;
3948 + matchByte = *(data - (reps[0] + 1));
3950 + posState = (position & p->pbMask);
3952 + curAnd1Price = curPrice + GET_PRICE_0(p->isMatch[state][posState]);
3954 + const CLzmaProb *probs = LIT_PROBS(position, *(data - 1));
3956 + (!IsCharState(state) ?
3957 + LitEnc_GetPriceMatched(probs, currentByte, matchByte, p->ProbPrices) :
3958 + LitEnc_GetPrice(probs, currentByte, p->ProbPrices));
3961 + nextOpt = &p->opt[cur + 1];
3963 + if (curAnd1Price < nextOpt->price)
3965 + nextOpt->price = curAnd1Price;
3966 + nextOpt->posPrev = cur;
3967 + MakeAsChar(nextOpt);
3968 + nextIsChar = True;
3971 + matchPrice = curPrice + GET_PRICE_1(p->isMatch[state][posState]);
3972 + repMatchPrice = matchPrice + GET_PRICE_1(p->isRep[state]);
3974 + if (matchByte == currentByte && !(nextOpt->posPrev < cur && nextOpt->backPrev == 0))
3976 + UInt32 shortRepPrice = repMatchPrice + GetRepLen1Price(p, state, posState);
3977 + if (shortRepPrice <= nextOpt->price)
3979 + nextOpt->price = shortRepPrice;
3980 + nextOpt->posPrev = cur;
3981 + MakeAsShortRep(nextOpt);
3982 + nextIsChar = True;
3987 + UInt32 temp = kNumOpts - 1 - cur;
3988 + if (temp < numAvailableBytesFull)
3989 + numAvailableBytesFull = temp;
3991 + numAvailableBytes = numAvailableBytesFull;
3993 + if (numAvailableBytes < 2)
3995 + if (numAvailableBytes > p->numFastBytes)
3996 + numAvailableBytes = p->numFastBytes;
3997 + if (!nextIsChar && matchByte != currentByte) /* speed optimization */
3999 + /* try Literal + rep0 */
4002 + const Byte *data2 = data - (reps[0] + 1);
4003 + UInt32 limit = p->numFastBytes + 1;
4004 + if (limit > numAvailableBytesFull)
4005 + limit = numAvailableBytesFull;
4007 + for (temp = 1; temp < limit && data[temp] == data2[temp]; temp++);
4008 + lenTest2 = temp - 1;
4009 + if (lenTest2 >= 2)
4011 + UInt32 state2 = kLiteralNextStates[state];
4012 + UInt32 posStateNext = (position + 1) & p->pbMask;
4013 + UInt32 nextRepMatchPrice = curAnd1Price +
4014 + GET_PRICE_1(p->isMatch[state2][posStateNext]) +
4015 + GET_PRICE_1(p->isRep[state2]);
4016 + /* for (; lenTest2 >= 2; lenTest2--) */
4018 + UInt32 curAndLenPrice;
4020 + UInt32 offset = cur + 1 + lenTest2;
4021 + while (lenEnd < offset)
4022 + p->opt[++lenEnd].price = kInfinityPrice;
4023 + curAndLenPrice = nextRepMatchPrice + GetRepPrice(p, 0, lenTest2, state2, posStateNext);
4024 + opt = &p->opt[offset];
4025 + if (curAndLenPrice < opt->price)
4027 + opt->price = curAndLenPrice;
4028 + opt->posPrev = cur + 1;
4029 + opt->backPrev = 0;
4030 + opt->prev1IsChar = True;
4031 + opt->prev2 = False;
4037 + startLen = 2; /* speed optimization */
4040 + for (repIndex = 0; repIndex < LZMA_NUM_REPS; repIndex++)
4043 + UInt32 lenTestTemp;
4045 + const Byte *data2 = data - (reps[repIndex] + 1);
4046 + if (data[0] != data2[0] || data[1] != data2[1])
4048 + for (lenTest = 2; lenTest < numAvailableBytes && data[lenTest] == data2[lenTest]; lenTest++);
4049 + while (lenEnd < cur + lenTest)
4050 + p->opt[++lenEnd].price = kInfinityPrice;
4051 + lenTestTemp = lenTest;
4052 + price = repMatchPrice + GetPureRepPrice(p, repIndex, state, posState);
4055 + UInt32 curAndLenPrice = price + p->repLenEnc.prices[posState][lenTest - 2];
4056 + COptimal *opt = &p->opt[cur + lenTest];
4057 + if (curAndLenPrice < opt->price)
4059 + opt->price = curAndLenPrice;
4060 + opt->posPrev = cur;
4061 + opt->backPrev = repIndex;
4062 + opt->prev1IsChar = False;
4065 + while (--lenTest >= 2);
4066 + lenTest = lenTestTemp;
4068 + if (repIndex == 0)
4069 + startLen = lenTest + 1;
4071 + /* if (_maxMode) */
4073 + UInt32 lenTest2 = lenTest + 1;
4074 + UInt32 limit = lenTest2 + p->numFastBytes;
4075 + UInt32 nextRepMatchPrice;
4076 + if (limit > numAvailableBytesFull)
4077 + limit = numAvailableBytesFull;
4078 + for (; lenTest2 < limit && data[lenTest2] == data2[lenTest2]; lenTest2++);
4079 + lenTest2 -= lenTest + 1;
4080 + if (lenTest2 >= 2)
4082 + UInt32 state2 = kRepNextStates[state];
4083 + UInt32 posStateNext = (position + lenTest) & p->pbMask;
4084 + UInt32 curAndLenCharPrice =
4085 + price + p->repLenEnc.prices[posState][lenTest - 2] +
4086 + GET_PRICE_0(p->isMatch[state2][posStateNext]) +
4087 + LitEnc_GetPriceMatched(LIT_PROBS(position + lenTest, data[lenTest - 1]),
4088 + data[lenTest], data2[lenTest], p->ProbPrices);
4089 + state2 = kLiteralNextStates[state2];
4090 + posStateNext = (position + lenTest + 1) & p->pbMask;
4091 + nextRepMatchPrice = curAndLenCharPrice +
4092 + GET_PRICE_1(p->isMatch[state2][posStateNext]) +
4093 + GET_PRICE_1(p->isRep[state2]);
4095 + /* for (; lenTest2 >= 2; lenTest2--) */
4097 + UInt32 curAndLenPrice;
4099 + UInt32 offset = cur + lenTest + 1 + lenTest2;
4100 + while (lenEnd < offset)
4101 + p->opt[++lenEnd].price = kInfinityPrice;
4102 + curAndLenPrice = nextRepMatchPrice + GetRepPrice(p, 0, lenTest2, state2, posStateNext);
4103 + opt = &p->opt[offset];
4104 + if (curAndLenPrice < opt->price)
4106 + opt->price = curAndLenPrice;
4107 + opt->posPrev = cur + lenTest + 1;
4108 + opt->backPrev = 0;
4109 + opt->prev1IsChar = True;
4110 + opt->prev2 = True;
4111 + opt->posPrev2 = cur;
4112 + opt->backPrev2 = repIndex;
4119 + /* for (UInt32 lenTest = 2; lenTest <= newLen; lenTest++) */
4120 + if (newLen > numAvailableBytes)
4122 + newLen = numAvailableBytes;
4123 + for (numDistancePairs = 0; newLen > matchDistances[numDistancePairs]; numDistancePairs += 2);
4124 + matchDistances[numDistancePairs] = newLen;
4125 + numDistancePairs += 2;
4127 + if (newLen >= startLen)
4129 + UInt32 normalMatchPrice = matchPrice + GET_PRICE_0(p->isRep[state]);
4130 + UInt32 offs, curBack, posSlot;
4132 + while (lenEnd < cur + newLen)
4133 + p->opt[++lenEnd].price = kInfinityPrice;
4136 + while (startLen > matchDistances[offs])
4138 + curBack = matchDistances[offs + 1];
4139 + GetPosSlot2(curBack, posSlot);
4140 + for (lenTest = /*2*/ startLen; ; lenTest++)
4142 + UInt32 curAndLenPrice = normalMatchPrice + p->lenEnc.prices[posState][lenTest - LZMA_MATCH_LEN_MIN];
4143 + UInt32 lenToPosState = GetLenToPosState(lenTest);
4145 + if (curBack < kNumFullDistances)
4146 + curAndLenPrice += p->distancesPrices[lenToPosState][curBack];
4148 + curAndLenPrice += p->posSlotPrices[lenToPosState][posSlot] + p->alignPrices[curBack & kAlignMask];
4150 + opt = &p->opt[cur + lenTest];
4151 + if (curAndLenPrice < opt->price)
4153 + opt->price = curAndLenPrice;
4154 + opt->posPrev = cur;
4155 + opt->backPrev = curBack + LZMA_NUM_REPS;
4156 + opt->prev1IsChar = False;
4159 + if (/*_maxMode && */lenTest == matchDistances[offs])
4161 + /* Try Match + Literal + Rep0 */
4162 + const Byte *data2 = data - (curBack + 1);
4163 + UInt32 lenTest2 = lenTest + 1;
4164 + UInt32 limit = lenTest2 + p->numFastBytes;
4165 + UInt32 nextRepMatchPrice;
4166 + if (limit > numAvailableBytesFull)
4167 + limit = numAvailableBytesFull;
4168 + for (; lenTest2 < limit && data[lenTest2] == data2[lenTest2]; lenTest2++);
4169 + lenTest2 -= lenTest + 1;
4170 + if (lenTest2 >= 2)
4172 + UInt32 state2 = kMatchNextStates[state];
4173 + UInt32 posStateNext = (position + lenTest) & p->pbMask;
4174 + UInt32 curAndLenCharPrice = curAndLenPrice +
4175 + GET_PRICE_0(p->isMatch[state2][posStateNext]) +
4176 + LitEnc_GetPriceMatched(LIT_PROBS(position + lenTest, data[lenTest - 1]),
4177 + data[lenTest], data2[lenTest], p->ProbPrices);
4178 + state2 = kLiteralNextStates[state2];
4179 + posStateNext = (posStateNext + 1) & p->pbMask;
4180 + nextRepMatchPrice = curAndLenCharPrice +
4181 + GET_PRICE_1(p->isMatch[state2][posStateNext]) +
4182 + GET_PRICE_1(p->isRep[state2]);
4184 + /* for (; lenTest2 >= 2; lenTest2--) */
4186 + UInt32 offset = cur + lenTest + 1 + lenTest2;
4187 + UInt32 curAndLenPrice;
4189 + while (lenEnd < offset)
4190 + p->opt[++lenEnd].price = kInfinityPrice;
4191 + curAndLenPrice = nextRepMatchPrice + GetRepPrice(p, 0, lenTest2, state2, posStateNext);
4192 + opt = &p->opt[offset];
4193 + if (curAndLenPrice < opt->price)
4195 + opt->price = curAndLenPrice;
4196 + opt->posPrev = cur + lenTest + 1;
4197 + opt->backPrev = 0;
4198 + opt->prev1IsChar = True;
4199 + opt->prev2 = True;
4200 + opt->posPrev2 = cur;
4201 + opt->backPrev2 = curBack + LZMA_NUM_REPS;
4206 + if (offs == numDistancePairs)
4208 + curBack = matchDistances[offs + 1];
4209 + if (curBack >= kNumFullDistances)
4210 + GetPosSlot2(curBack, posSlot);
4217 +#define ChangePair(smallDist, bigDist) (((bigDist) >> 7) > (smallDist))
4219 +static UInt32 GetOptimumFast(CLzmaEnc *p, UInt32 *backRes)
4221 + UInt32 numAvailableBytes = p->matchFinder.GetNumAvailableBytes(p->matchFinderObj);
4222 + UInt32 lenMain, numDistancePairs;
4224 + UInt32 repLens[LZMA_NUM_REPS];
4225 + UInt32 repMaxIndex, i;
4226 + UInt32 *matchDistances;
4229 + if (!p->longestMatchWasFound)
4231 + lenMain = ReadMatchDistances(p, &numDistancePairs);
4235 + lenMain = p->longestMatchLength;
4236 + numDistancePairs = p->numDistancePairs;
4237 + p->longestMatchWasFound = False;
4240 + data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - 1;
4241 + if (numAvailableBytes > LZMA_MATCH_LEN_MAX)
4242 + numAvailableBytes = LZMA_MATCH_LEN_MAX;
4243 + if (numAvailableBytes < 2)
4245 + *backRes = (UInt32)(-1);
4251 + for (i = 0; i < LZMA_NUM_REPS; i++)
4253 + const Byte *data2 = data - (p->reps[i] + 1);
4255 + if (data[0] != data2[0] || data[1] != data2[1])
4260 + for (len = 2; len < numAvailableBytes && data[len] == data2[len]; len++);
4261 + if (len >= p->numFastBytes)
4264 + MovePos(p, len - 1);
4268 + if (len > repLens[repMaxIndex])
4271 + matchDistances = p->matchDistances;
4272 + if (lenMain >= p->numFastBytes)
4274 + *backRes = matchDistances[numDistancePairs - 1] + LZMA_NUM_REPS;
4275 + MovePos(p, lenMain - 1);
4279 + backMain = 0; /* for GCC */
4282 + backMain = matchDistances[numDistancePairs - 1];
4283 + while (numDistancePairs > 2 && lenMain == matchDistances[numDistancePairs - 4] + 1)
4285 + if (!ChangePair(matchDistances[numDistancePairs - 3], backMain))
4287 + numDistancePairs -= 2;
4288 + lenMain = matchDistances[numDistancePairs - 2];
4289 + backMain = matchDistances[numDistancePairs - 1];
4291 + if (lenMain == 2 && backMain >= 0x80)
4295 + if (repLens[repMaxIndex] >= 2)
4297 + if (repLens[repMaxIndex] + 1 >= lenMain ||
4298 + (repLens[repMaxIndex] + 2 >= lenMain && (backMain > (1 << 9))) ||
4299 + (repLens[repMaxIndex] + 3 >= lenMain && (backMain > (1 << 15))))
4302 + *backRes = repMaxIndex;
4303 + lenRes = repLens[repMaxIndex];
4304 + MovePos(p, lenRes - 1);
4309 + if (lenMain >= 2 && numAvailableBytes > 2)
4312 + numAvailableBytes = p->matchFinder.GetNumAvailableBytes(p->matchFinderObj);
4313 + p->longestMatchLength = ReadMatchDistances(p, &p->numDistancePairs);
4314 + if (p->longestMatchLength >= 2)
4316 + UInt32 newDistance = matchDistances[p->numDistancePairs - 1];
4317 + if ((p->longestMatchLength >= lenMain && newDistance < backMain) ||
4318 + (p->longestMatchLength == lenMain + 1 && !ChangePair(backMain, newDistance)) ||
4319 + (p->longestMatchLength > lenMain + 1) ||
4320 + (p->longestMatchLength + 1 >= lenMain && lenMain >= 3 && ChangePair(newDistance, backMain)))
4322 + p->longestMatchWasFound = True;
4323 + *backRes = (UInt32)(-1);
4327 + data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - 1;
4328 + for (i = 0; i < LZMA_NUM_REPS; i++)
4331 + const Byte *data2 = data - (p->reps[i] + 1);
4332 + if (data[1] != data2[1] || data[2] != data2[2])
4337 + for (len = 2; len < numAvailableBytes && data[len] == data2[len]; len++);
4338 + if (len + 1 >= lenMain)
4340 + p->longestMatchWasFound = True;
4341 + *backRes = (UInt32)(-1);
4345 + *backRes = backMain + LZMA_NUM_REPS;
4346 + MovePos(p, lenMain - 2);
4349 + *backRes = (UInt32)(-1);
4353 +static void WriteEndMarker(CLzmaEnc *p, UInt32 posState)
4356 + RangeEnc_EncodeBit(&p->rc, &p->isMatch[p->state][posState], 1);
4357 + RangeEnc_EncodeBit(&p->rc, &p->isRep[p->state], 0);
4358 + p->state = kMatchNextStates[p->state];
4359 + len = LZMA_MATCH_LEN_MIN;
4360 + LenEnc_Encode2(&p->lenEnc, &p->rc, len - LZMA_MATCH_LEN_MIN, posState, !p->fastMode, p->ProbPrices);
4361 + RcTree_Encode(&p->rc, p->posSlotEncoder[GetLenToPosState(len)], kNumPosSlotBits, (1 << kNumPosSlotBits) - 1);
4362 + RangeEnc_EncodeDirectBits(&p->rc, (((UInt32)1 << 30) - 1) >> kNumAlignBits, 30 - kNumAlignBits);
4363 + RcTree_ReverseEncode(&p->rc, p->posAlignEncoder, kNumAlignBits, kAlignMask);
4366 +static SRes CheckErrors(CLzmaEnc *p)
4368 + if (p->result != SZ_OK)
4370 + if (p->rc.res != SZ_OK)
4371 + p->result = SZ_ERROR_WRITE;
4372 + if (p->matchFinderBase.result != SZ_OK)
4373 + p->result = SZ_ERROR_READ;
4374 + if (p->result != SZ_OK)
4375 + p->finished = True;
4379 +static SRes Flush(CLzmaEnc *p, UInt32 nowPos)
4381 + /* ReleaseMFStream(); */
4382 + p->finished = True;
4383 + if (p->writeEndMark)
4384 + WriteEndMarker(p, nowPos & p->pbMask);
4385 + RangeEnc_FlushData(&p->rc);
4386 + RangeEnc_FlushStream(&p->rc);
4387 + return CheckErrors(p);
4390 +static void FillAlignPrices(CLzmaEnc *p)
4393 + for (i = 0; i < kAlignTableSize; i++)
4394 + p->alignPrices[i] = RcTree_ReverseGetPrice(p->posAlignEncoder, kNumAlignBits, i, p->ProbPrices);
4395 + p->alignPriceCount = 0;
4398 +static void FillDistancesPrices(CLzmaEnc *p)
4400 + UInt32 tempPrices[kNumFullDistances];
4401 + UInt32 i, lenToPosState;
4402 + for (i = kStartPosModelIndex; i < kNumFullDistances; i++)
4404 + UInt32 posSlot = GetPosSlot1(i);
4405 + UInt32 footerBits = ((posSlot >> 1) - 1);
4406 + UInt32 base = ((2 | (posSlot & 1)) << footerBits);
4407 + tempPrices[i] = RcTree_ReverseGetPrice(p->posEncoders + base - posSlot - 1, footerBits, i - base, p->ProbPrices);
4410 + for (lenToPosState = 0; lenToPosState < kNumLenToPosStates; lenToPosState++)
4413 + const CLzmaProb *encoder = p->posSlotEncoder[lenToPosState];
4414 + UInt32 *posSlotPrices = p->posSlotPrices[lenToPosState];
4415 + for (posSlot = 0; posSlot < p->distTableSize; posSlot++)
4416 + posSlotPrices[posSlot] = RcTree_GetPrice(encoder, kNumPosSlotBits, posSlot, p->ProbPrices);
4417 + for (posSlot = kEndPosModelIndex; posSlot < p->distTableSize; posSlot++)
4418 + posSlotPrices[posSlot] += ((((posSlot >> 1) - 1) - kNumAlignBits) << kNumBitPriceShiftBits);
4421 + UInt32 *distancesPrices = p->distancesPrices[lenToPosState];
4423 + for (i = 0; i < kStartPosModelIndex; i++)
4424 + distancesPrices[i] = posSlotPrices[i];
4425 + for (; i < kNumFullDistances; i++)
4426 + distancesPrices[i] = posSlotPrices[GetPosSlot1(i)] + tempPrices[i];
4429 + p->matchPriceCount = 0;
4432 +static void LzmaEnc_Construct(CLzmaEnc *p)
4434 + RangeEnc_Construct(&p->rc);
4435 + MatchFinder_Construct(&p->matchFinderBase);
4436 + #ifdef COMPRESS_MF_MT
4437 + MatchFinderMt_Construct(&p->matchFinderMt);
4438 + p->matchFinderMt.MatchFinder = &p->matchFinderBase;
4442 + CLzmaEncProps props;
4443 + LzmaEncProps_Init(&props);
4444 + LzmaEnc_SetProps(p, &props);
4447 + #ifndef LZMA_LOG_BSR
4448 + LzmaEnc_FastPosInit(p->g_FastPos);
4451 + LzmaEnc_InitPriceTables(p->ProbPrices);
4453 + p->saveState.litProbs = 0;
4456 +CLzmaEncHandle LzmaEnc_Create(ISzAlloc *alloc)
4459 + p = alloc->Alloc(alloc, sizeof(CLzmaEnc));
4461 + LzmaEnc_Construct((CLzmaEnc *)p);
4465 +static void LzmaEnc_FreeLits(CLzmaEnc *p, ISzAlloc *alloc)
4467 + alloc->Free(alloc, p->litProbs);
4468 + alloc->Free(alloc, p->saveState.litProbs);
4470 + p->saveState.litProbs = 0;
4473 +static void LzmaEnc_Destruct(CLzmaEnc *p, ISzAlloc *alloc, ISzAlloc *allocBig)
4475 + #ifdef COMPRESS_MF_MT
4476 + MatchFinderMt_Destruct(&p->matchFinderMt, allocBig);
4478 + MatchFinder_Free(&p->matchFinderBase, allocBig);
4479 + LzmaEnc_FreeLits(p, alloc);
4480 + RangeEnc_Free(&p->rc, alloc);
4483 +void LzmaEnc_Destroy(CLzmaEncHandle p, ISzAlloc *alloc, ISzAlloc *allocBig)
4485 + LzmaEnc_Destruct((CLzmaEnc *)p, alloc, allocBig);
4486 + alloc->Free(alloc, p);
4489 +static SRes LzmaEnc_CodeOneBlock(CLzmaEnc *p, Bool useLimits, UInt32 maxPackSize, UInt32 maxUnpackSize)
4491 + UInt32 nowPos32, startPos32;
4492 + if (p->inStream != 0)
4494 + p->matchFinderBase.stream = p->inStream;
4495 + p->matchFinder.Init(p->matchFinderObj);
4501 + RINOK(CheckErrors(p));
4503 + nowPos32 = (UInt32)p->nowPos64;
4504 + startPos32 = nowPos32;
4506 + if (p->nowPos64 == 0)
4508 + UInt32 numDistancePairs;
4510 + if (p->matchFinder.GetNumAvailableBytes(p->matchFinderObj) == 0)
4511 + return Flush(p, nowPos32);
4512 + ReadMatchDistances(p, &numDistancePairs);
4513 + RangeEnc_EncodeBit(&p->rc, &p->isMatch[p->state][0], 0);
4514 + p->state = kLiteralNextStates[p->state];
4515 + curByte = p->matchFinder.GetIndexByte(p->matchFinderObj, 0 - p->additionalOffset);
4516 + LitEnc_Encode(&p->rc, p->litProbs, curByte);
4517 + p->additionalOffset--;
4521 + if (p->matchFinder.GetNumAvailableBytes(p->matchFinderObj) != 0)
4524 + UInt32 pos, len, posState;
4527 + len = GetOptimumFast(p, &pos);
4529 + len = GetOptimum(p, nowPos32, &pos);
4532 + printf("\n pos = %4X, len = %d pos = %d", nowPos32, len, pos);
4535 + posState = nowPos32 & p->pbMask;
4536 + if (len == 1 && pos == 0xFFFFFFFF)
4542 + RangeEnc_EncodeBit(&p->rc, &p->isMatch[p->state][posState], 0);
4543 + data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - p->additionalOffset;
4545 + probs = LIT_PROBS(nowPos32, *(data - 1));
4546 + if (IsCharState(p->state))
4547 + LitEnc_Encode(&p->rc, probs, curByte);
4549 + LitEnc_EncodeMatched(&p->rc, probs, curByte, *(data - p->reps[0] - 1));
4550 + p->state = kLiteralNextStates[p->state];
4554 + RangeEnc_EncodeBit(&p->rc, &p->isMatch[p->state][posState], 1);
4555 + if (pos < LZMA_NUM_REPS)
4557 + RangeEnc_EncodeBit(&p->rc, &p->isRep[p->state], 1);
4560 + RangeEnc_EncodeBit(&p->rc, &p->isRepG0[p->state], 0);
4561 + RangeEnc_EncodeBit(&p->rc, &p->isRep0Long[p->state][posState], ((len == 1) ? 0 : 1));
4565 + UInt32 distance = p->reps[pos];
4566 + RangeEnc_EncodeBit(&p->rc, &p->isRepG0[p->state], 1);
4568 + RangeEnc_EncodeBit(&p->rc, &p->isRepG1[p->state], 0);
4571 + RangeEnc_EncodeBit(&p->rc, &p->isRepG1[p->state], 1);
4572 + RangeEnc_EncodeBit(&p->rc, &p->isRepG2[p->state], pos - 2);
4574 + p->reps[3] = p->reps[2];
4575 + p->reps[2] = p->reps[1];
4577 + p->reps[1] = p->reps[0];
4578 + p->reps[0] = distance;
4581 + p->state = kShortRepNextStates[p->state];
4584 + LenEnc_Encode2(&p->repLenEnc, &p->rc, len - LZMA_MATCH_LEN_MIN, posState, !p->fastMode, p->ProbPrices);
4585 + p->state = kRepNextStates[p->state];
4591 + RangeEnc_EncodeBit(&p->rc, &p->isRep[p->state], 0);
4592 + p->state = kMatchNextStates[p->state];
4593 + LenEnc_Encode2(&p->lenEnc, &p->rc, len - LZMA_MATCH_LEN_MIN, posState, !p->fastMode, p->ProbPrices);
4594 + pos -= LZMA_NUM_REPS;
4595 + GetPosSlot(pos, posSlot);
4596 + RcTree_Encode(&p->rc, p->posSlotEncoder[GetLenToPosState(len)], kNumPosSlotBits, posSlot);
4598 + if (posSlot >= kStartPosModelIndex)
4600 + UInt32 footerBits = ((posSlot >> 1) - 1);
4601 + UInt32 base = ((2 | (posSlot & 1)) << footerBits);
4602 + UInt32 posReduced = pos - base;
4604 + if (posSlot < kEndPosModelIndex)
4605 + RcTree_ReverseEncode(&p->rc, p->posEncoders + base - posSlot - 1, footerBits, posReduced);
4608 + RangeEnc_EncodeDirectBits(&p->rc, posReduced >> kNumAlignBits, footerBits - kNumAlignBits);
4609 + RcTree_ReverseEncode(&p->rc, p->posAlignEncoder, kNumAlignBits, posReduced & kAlignMask);
4610 + p->alignPriceCount++;
4613 + p->reps[3] = p->reps[2];
4614 + p->reps[2] = p->reps[1];
4615 + p->reps[1] = p->reps[0];
4617 + p->matchPriceCount++;
4620 + p->additionalOffset -= len;
4622 + if (p->additionalOffset == 0)
4627 + if (p->matchPriceCount >= (1 << 7))
4628 + FillDistancesPrices(p);
4629 + if (p->alignPriceCount >= kAlignTableSize)
4630 + FillAlignPrices(p);
4632 + if (p->matchFinder.GetNumAvailableBytes(p->matchFinderObj) == 0)
4634 + processed = nowPos32 - startPos32;
4637 + if (processed + kNumOpts + 300 >= maxUnpackSize ||
4638 + RangeEnc_GetProcessed(&p->rc) + kNumOpts * 2 >= maxPackSize)
4641 + else if (processed >= (1 << 15))
4643 + p->nowPos64 += nowPos32 - startPos32;
4644 + return CheckErrors(p);
4648 + p->nowPos64 += nowPos32 - startPos32;
4649 + return Flush(p, nowPos32);
4652 +#define kBigHashDicLimit ((UInt32)1 << 24)
4654 +static SRes LzmaEnc_Alloc(CLzmaEnc *p, UInt32 keepWindowSize, ISzAlloc *alloc, ISzAlloc *allocBig)
4656 + UInt32 beforeSize = kNumOpts;
4658 + if (!RangeEnc_Alloc(&p->rc, alloc))
4659 + return SZ_ERROR_MEM;
4660 + btMode = (p->matchFinderBase.btMode != 0);
4661 + #ifdef COMPRESS_MF_MT
4662 + p->mtMode = (p->multiThread && !p->fastMode && btMode);
4666 + unsigned lclp = p->lc + p->lp;
4667 + if (p->litProbs == 0 || p->saveState.litProbs == 0 || p->lclp != lclp)
4669 + LzmaEnc_FreeLits(p, alloc);
4670 + p->litProbs = (CLzmaProb *)alloc->Alloc(alloc, (0x300 << lclp) * sizeof(CLzmaProb));
4671 + p->saveState.litProbs = (CLzmaProb *)alloc->Alloc(alloc, (0x300 << lclp) * sizeof(CLzmaProb));
4672 + if (p->litProbs == 0 || p->saveState.litProbs == 0)
4674 + LzmaEnc_FreeLits(p, alloc);
4675 + return SZ_ERROR_MEM;
4681 + p->matchFinderBase.bigHash = (p->dictSize > kBigHashDicLimit);
4683 + if (beforeSize + p->dictSize < keepWindowSize)
4684 + beforeSize = keepWindowSize - p->dictSize;
4686 + #ifdef COMPRESS_MF_MT
4689 + RINOK(MatchFinderMt_Create(&p->matchFinderMt, p->dictSize, beforeSize, p->numFastBytes, LZMA_MATCH_LEN_MAX, allocBig));
4690 + p->matchFinderObj = &p->matchFinderMt;
4691 + MatchFinderMt_CreateVTable(&p->matchFinderMt, &p->matchFinder);
4696 + if (!MatchFinder_Create(&p->matchFinderBase, p->dictSize, beforeSize, p->numFastBytes, LZMA_MATCH_LEN_MAX, allocBig))
4697 + return SZ_ERROR_MEM;
4698 + p->matchFinderObj = &p->matchFinderBase;
4699 + MatchFinder_CreateVTable(&p->matchFinderBase, &p->matchFinder);
4704 +static void LzmaEnc_Init(CLzmaEnc *p)
4708 + for(i = 0 ; i < LZMA_NUM_REPS; i++)
4711 + RangeEnc_Init(&p->rc);
4714 + for (i = 0; i < kNumStates; i++)
4717 + for (j = 0; j < LZMA_NUM_PB_STATES_MAX; j++)
4719 + p->isMatch[i][j] = kProbInitValue;
4720 + p->isRep0Long[i][j] = kProbInitValue;
4722 + p->isRep[i] = kProbInitValue;
4723 + p->isRepG0[i] = kProbInitValue;
4724 + p->isRepG1[i] = kProbInitValue;
4725 + p->isRepG2[i] = kProbInitValue;
4729 + UInt32 num = 0x300 << (p->lp + p->lc);
4730 + for (i = 0; i < num; i++)
4731 + p->litProbs[i] = kProbInitValue;
4735 + for (i = 0; i < kNumLenToPosStates; i++)
4737 + CLzmaProb *probs = p->posSlotEncoder[i];
4739 + for (j = 0; j < (1 << kNumPosSlotBits); j++)
4740 + probs[j] = kProbInitValue;
4744 + for(i = 0; i < kNumFullDistances - kEndPosModelIndex; i++)
4745 + p->posEncoders[i] = kProbInitValue;
4748 + LenEnc_Init(&p->lenEnc.p);
4749 + LenEnc_Init(&p->repLenEnc.p);
4751 + for (i = 0; i < (1 << kNumAlignBits); i++)
4752 + p->posAlignEncoder[i] = kProbInitValue;
4754 + p->longestMatchWasFound = False;
4755 + p->optimumEndIndex = 0;
4756 + p->optimumCurrentIndex = 0;
4757 + p->additionalOffset = 0;
4759 + p->pbMask = (1 << p->pb) - 1;
4760 + p->lpMask = (1 << p->lp) - 1;
4763 +static void LzmaEnc_InitPrices(CLzmaEnc *p)
4767 + FillDistancesPrices(p);
4768 + FillAlignPrices(p);
4771 + p->lenEnc.tableSize =
4772 + p->repLenEnc.tableSize =
4773 + p->numFastBytes + 1 - LZMA_MATCH_LEN_MIN;
4774 + LenPriceEnc_UpdateTables(&p->lenEnc, 1 << p->pb, p->ProbPrices);
4775 + LenPriceEnc_UpdateTables(&p->repLenEnc, 1 << p->pb, p->ProbPrices);
4778 +static SRes LzmaEnc_AllocAndInit(CLzmaEnc *p, UInt32 keepWindowSize, ISzAlloc *alloc, ISzAlloc *allocBig)
4781 + for (i = 0; i < (UInt32)kDicLogSizeMaxCompress; i++)
4782 + if (p->dictSize <= ((UInt32)1 << i))
4784 + p->distTableSize = i * 2;
4786 + p->finished = False;
4787 + p->result = SZ_OK;
4788 + RINOK(LzmaEnc_Alloc(p, keepWindowSize, alloc, allocBig));
4790 + LzmaEnc_InitPrices(p);
4795 +static SRes LzmaEnc_Prepare(CLzmaEncHandle pp, ISeqInStream *inStream, ISeqOutStream *outStream,
4796 + ISzAlloc *alloc, ISzAlloc *allocBig)
4798 + CLzmaEnc *p = (CLzmaEnc *)pp;
4799 + p->inStream = inStream;
4800 + p->rc.outStream = outStream;
4801 + return LzmaEnc_AllocAndInit(p, 0, alloc, allocBig);
4804 +static SRes LzmaEnc_PrepareForLzma2(CLzmaEncHandle pp,
4805 + ISeqInStream *inStream, UInt32 keepWindowSize,
4806 + ISzAlloc *alloc, ISzAlloc *allocBig)
4808 + CLzmaEnc *p = (CLzmaEnc *)pp;
4809 + p->inStream = inStream;
4810 + return LzmaEnc_AllocAndInit(p, keepWindowSize, alloc, allocBig);
4813 +static void LzmaEnc_SetInputBuf(CLzmaEnc *p, const Byte *src, SizeT srcLen)
4815 + p->seqBufInStream.funcTable.Read = MyRead;
4816 + p->seqBufInStream.data = src;
4817 + p->seqBufInStream.rem = srcLen;
4820 +static SRes LzmaEnc_MemPrepare(CLzmaEncHandle pp, const Byte *src, SizeT srcLen,
4821 + UInt32 keepWindowSize, ISzAlloc *alloc, ISzAlloc *allocBig)
4823 + CLzmaEnc *p = (CLzmaEnc *)pp;
4824 + LzmaEnc_SetInputBuf(p, src, srcLen);
4825 + p->inStream = &p->seqBufInStream.funcTable;
4826 + return LzmaEnc_AllocAndInit(p, keepWindowSize, alloc, allocBig);
4829 +static void LzmaEnc_Finish(CLzmaEncHandle pp)
4831 + #ifdef COMPRESS_MF_MT
4832 + CLzmaEnc *p = (CLzmaEnc *)pp;
4834 + MatchFinderMt_ReleaseStream(&p->matchFinderMt);
4838 +typedef struct _CSeqOutStreamBuf
4840 + ISeqOutStream funcTable;
4844 +} CSeqOutStreamBuf;
4846 +static size_t MyWrite(void *pp, const void *data, size_t size)
4848 + CSeqOutStreamBuf *p = (CSeqOutStreamBuf *)pp;
4849 + if (p->rem < size)
4852 + p->overflow = True;
4854 + memcpy(p->data, data, size);
4861 +static UInt32 LzmaEnc_GetNumAvailableBytes(CLzmaEncHandle pp)
4863 + const CLzmaEnc *p = (CLzmaEnc *)pp;
4864 + return p->matchFinder.GetNumAvailableBytes(p->matchFinderObj);
4867 +static const Byte *LzmaEnc_GetCurBuf(CLzmaEncHandle pp)
4869 + const CLzmaEnc *p = (CLzmaEnc *)pp;
4870 + return p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - p->additionalOffset;
4873 +static SRes LzmaEnc_CodeOneMemBlock(CLzmaEncHandle pp, Bool reInit,
4874 + Byte *dest, size_t *destLen, UInt32 desiredPackSize, UInt32 *unpackSize)
4876 + CLzmaEnc *p = (CLzmaEnc *)pp;
4879 + CSeqOutStreamBuf outStream;
4881 + outStream.funcTable.Write = MyWrite;
4882 + outStream.data = dest;
4883 + outStream.rem = *destLen;
4884 + outStream.overflow = False;
4886 + p->writeEndMark = False;
4887 + p->finished = False;
4888 + p->result = SZ_OK;
4892 + LzmaEnc_InitPrices(p);
4893 + nowPos64 = p->nowPos64;
4894 + RangeEnc_Init(&p->rc);
4895 + p->rc.outStream = &outStream.funcTable;
4897 + res = LzmaEnc_CodeOneBlock(pp, True, desiredPackSize, *unpackSize);
4899 + *unpackSize = (UInt32)(p->nowPos64 - nowPos64);
4900 + *destLen -= outStream.rem;
4901 + if (outStream.overflow)
4902 + return SZ_ERROR_OUTPUT_EOF;
4907 +SRes LzmaEnc_Encode(CLzmaEncHandle pp, ISeqOutStream *outStream, ISeqInStream *inStream, ICompressProgress *progress,
4908 + ISzAlloc *alloc, ISzAlloc *allocBig)
4910 + CLzmaEnc *p = (CLzmaEnc *)pp;
4913 + #ifdef COMPRESS_MF_MT
4914 + Byte allocaDummy[0x300];
4916 + for (i = 0; i < 16; i++)
4917 + allocaDummy[i] = (Byte)i;
4920 + RINOK(LzmaEnc_Prepare(pp, inStream, outStream, alloc, allocBig));
4924 + res = LzmaEnc_CodeOneBlock(pp, False, 0, 0);
4925 + if (res != SZ_OK || p->finished != 0)
4927 + if (progress != 0)
4929 + res = progress->Progress(progress, p->nowPos64, RangeEnc_GetProcessed(&p->rc));
4932 + res = SZ_ERROR_PROGRESS;
4937 + LzmaEnc_Finish(pp);
4941 +SRes LzmaEnc_WriteProperties(CLzmaEncHandle pp, Byte *props, SizeT *size)
4943 + CLzmaEnc *p = (CLzmaEnc *)pp;
4945 + UInt32 dictSize = p->dictSize;
4946 + if (*size < LZMA_PROPS_SIZE)
4947 + return SZ_ERROR_PARAM;
4948 + *size = LZMA_PROPS_SIZE;
4949 + props[0] = (Byte)((p->pb * 5 + p->lp) * 9 + p->lc);
4951 + for (i = 11; i <= 30; i++)
4953 + if (dictSize <= ((UInt32)2 << i))
4955 + dictSize = (2 << i);
4958 + if (dictSize <= ((UInt32)3 << i))
4960 + dictSize = (3 << i);
4965 + for (i = 0; i < 4; i++)
4966 + props[1 + i] = (Byte)(dictSize >> (8 * i));
4970 +SRes LzmaEnc_MemEncode(CLzmaEncHandle pp, Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen,
4971 + int writeEndMark, ICompressProgress *progress, ISzAlloc *alloc, ISzAlloc *allocBig)
4974 + CLzmaEnc *p = (CLzmaEnc *)pp;
4976 + CSeqOutStreamBuf outStream;
4978 + LzmaEnc_SetInputBuf(p, src, srcLen);
4980 + outStream.funcTable.Write = MyWrite;
4981 + outStream.data = dest;
4982 + outStream.rem = *destLen;
4983 + outStream.overflow = False;
4985 + p->writeEndMark = writeEndMark;
4986 + res = LzmaEnc_Encode(pp, &outStream.funcTable, &p->seqBufInStream.funcTable,
4987 + progress, alloc, allocBig);
4989 + *destLen -= outStream.rem;
4990 + if (outStream.overflow)
4991 + return SZ_ERROR_OUTPUT_EOF;
4995 +SRes LzmaEncode(Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen,
4996 + const CLzmaEncProps *props, Byte *propsEncoded, SizeT *propsSize, int writeEndMark,
4997 + ICompressProgress *progress, ISzAlloc *alloc, ISzAlloc *allocBig)
4999 + CLzmaEnc *p = (CLzmaEnc *)LzmaEnc_Create(alloc);
5002 + return SZ_ERROR_MEM;
5004 + res = LzmaEnc_SetProps(p, props);
5007 + res = LzmaEnc_WriteProperties(p, propsEncoded, propsSize);
5009 + res = LzmaEnc_MemEncode(p, dest, destLen, src, srcLen,
5010 + writeEndMark, progress, alloc, allocBig);
5013 + LzmaEnc_Destroy(p, alloc, allocBig);
5016 --- a/jffsX-utils/mkfs.jffs2.c
5017 +++ b/jffsX-utils/mkfs.jffs2.c
5018 @@ -1666,11 +1666,11 @@ int main(int argc, char **argv)
5020 erase_block_size *= units;
5022 - /* If it's less than 8KiB, they're not allowed */
5023 - if (erase_block_size < 0x2000) {
5024 - fprintf(stderr, "Erase size 0x%x too small. Increasing to 8KiB minimum\n",
5025 + /* If it's less than 4KiB, they're not allowed */
5026 + if (erase_block_size < 0x1000) {
5027 + fprintf(stderr, "Erase size 0x%x too small. Increasing to 4KiB minimum\n",
5029 - erase_block_size = 0x2000;
5030 + erase_block_size = 0x1000;