LzmaEnc.c 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357
  1. /* LzmaEnc.c -- LZMA Encoder
  2. 2017-04-03 : Igor Pavlov : Public domain */
  3. #include "Precomp.h"
  4. #include <string.h>
  5. /* #define SHOW_STAT */
  6. /* #define SHOW_STAT2 */
  7. #if defined(SHOW_STAT) || defined(SHOW_STAT2)
  8. #include <stdio.h>
  9. #endif
  10. #include "LzmaEnc.h"
  11. #include "LzFind.h"
  12. #ifndef _7ZIP_ST
  13. #include "LzFindMt.h"
  14. #endif
  15. #ifdef SHOW_STAT
  16. static unsigned g_STAT_OFFSET = 0;
  17. #endif
  18. #define kMaxHistorySize ((UInt32)3 << 29)
  19. /* #define kMaxHistorySize ((UInt32)7 << 29) */
  20. #define kBlockSizeMax ((1 << LZMA_NUM_BLOCK_SIZE_BITS) - 1)
  21. #define kBlockSize (9 << 10)
  22. #define kUnpackBlockSize (1 << 18)
  23. #define kMatchArraySize (1 << 21)
  24. #define kMatchRecordMaxSize ((LZMA_MATCH_LEN_MAX * 2 + 3) * LZMA_MATCH_LEN_MAX)
  25. #define kNumMaxDirectBits (31)
  26. #define kNumTopBits 24
  27. #define kTopValue ((UInt32)1 << kNumTopBits)
  28. #define kNumBitModelTotalBits 11
  29. #define kBitModelTotal (1 << kNumBitModelTotalBits)
  30. #define kNumMoveBits 5
  31. #define kProbInitValue (kBitModelTotal >> 1)
  32. #define kNumMoveReducingBits 4
  33. #define kNumBitPriceShiftBits 4
  34. #define kBitPrice (1 << kNumBitPriceShiftBits)
  35. void LzmaEncProps_Init(CLzmaEncProps *p)
  36. {
  37. p->level = 5;
  38. p->dictSize = p->mc = 0;
  39. p->reduceSize = (UInt64)(Int64)-1;
  40. p->lc = p->lp = p->pb = p->algo = p->fb = p->btMode = p->numHashBytes = p->numThreads = -1;
  41. p->writeEndMark = 0;
  42. }
  43. void LzmaEncProps_Normalize(CLzmaEncProps *p)
  44. {
  45. int level = p->level;
  46. if (level < 0) level = 5;
  47. p->level = level;
  48. if (p->dictSize == 0) p->dictSize = (level <= 5 ? (1 << (level * 2 + 14)) : (level == 6 ? (1 << 25) : (1 << 26)));
  49. if (p->dictSize > p->reduceSize)
  50. {
  51. unsigned i;
  52. for (i = 11; i <= 30; i++)
  53. {
  54. if ((UInt32)p->reduceSize <= ((UInt32)2 << i)) { p->dictSize = ((UInt32)2 << i); break; }
  55. if ((UInt32)p->reduceSize <= ((UInt32)3 << i)) { p->dictSize = ((UInt32)3 << i); break; }
  56. }
  57. }
  58. if (p->lc < 0) p->lc = 3;
  59. if (p->lp < 0) p->lp = 0;
  60. if (p->pb < 0) p->pb = 2;
  61. if (p->algo < 0) p->algo = (level < 5 ? 0 : 1);
  62. if (p->fb < 0) p->fb = (level < 7 ? 32 : 64);
  63. if (p->btMode < 0) p->btMode = (p->algo == 0 ? 0 : 1);
  64. if (p->numHashBytes < 0) p->numHashBytes = 4;
  65. if (p->mc == 0) p->mc = (16 + (p->fb >> 1)) >> (p->btMode ? 0 : 1);
  66. if (p->numThreads < 0)
  67. p->numThreads =
  68. #ifndef _7ZIP_ST
  69. ((p->btMode && p->algo) ? 2 : 1);
  70. #else
  71. 1;
  72. #endif
  73. }
  74. UInt32 LzmaEncProps_GetDictSize(const CLzmaEncProps *props2)
  75. {
  76. CLzmaEncProps props = *props2;
  77. LzmaEncProps_Normalize(&props);
  78. return props.dictSize;
  79. }
  80. #if (_MSC_VER >= 1400)
  81. /* BSR code is fast for some new CPUs */
  82. /* #define LZMA_LOG_BSR */
  83. #endif
  84. #ifdef LZMA_LOG_BSR
  85. #define kDicLogSizeMaxCompress 32
  86. #define BSR2_RET(pos, res) { unsigned long zz; _BitScanReverse(&zz, (pos)); res = (zz + zz) + ((pos >> (zz - 1)) & 1); }
  87. static UInt32 GetPosSlot1(UInt32 pos)
  88. {
  89. UInt32 res;
  90. BSR2_RET(pos, res);
  91. return res;
  92. }
  93. #define GetPosSlot2(pos, res) { BSR2_RET(pos, res); }
  94. #define GetPosSlot(pos, res) { if (pos < 2) res = pos; else BSR2_RET(pos, res); }
  95. #else
  96. #define kNumLogBits (9 + sizeof(size_t) / 2)
  97. /* #define kNumLogBits (11 + sizeof(size_t) / 8 * 3) */
  98. #define kDicLogSizeMaxCompress ((kNumLogBits - 1) * 2 + 7)
  99. static void LzmaEnc_FastPosInit(Byte *g_FastPos)
  100. {
  101. unsigned slot;
  102. g_FastPos[0] = 0;
  103. g_FastPos[1] = 1;
  104. g_FastPos += 2;
  105. for (slot = 2; slot < kNumLogBits * 2; slot++)
  106. {
  107. size_t k = ((size_t)1 << ((slot >> 1) - 1));
  108. size_t j;
  109. for (j = 0; j < k; j++)
  110. g_FastPos[j] = (Byte)slot;
  111. g_FastPos += k;
  112. }
  113. }
  114. /* we can use ((limit - pos) >> 31) only if (pos < ((UInt32)1 << 31)) */
  115. /*
  116. #define BSR2_RET(pos, res) { UInt32 zz = 6 + ((kNumLogBits - 1) & \
  117. (0 - (((((UInt32)1 << (kNumLogBits + 6)) - 1) - pos) >> 31))); \
  118. res = p->g_FastPos[pos >> zz] + (zz * 2); }
  119. */
  120. /*
  121. #define BSR2_RET(pos, res) { UInt32 zz = 6 + ((kNumLogBits - 1) & \
  122. (0 - (((((UInt32)1 << (kNumLogBits)) - 1) - (pos >> 6)) >> 31))); \
  123. res = p->g_FastPos[pos >> zz] + (zz * 2); }
  124. */
  125. #define BSR2_RET(pos, res) { UInt32 zz = (pos < (1 << (kNumLogBits + 6))) ? 6 : 6 + kNumLogBits - 1; \
  126. res = p->g_FastPos[pos >> zz] + (zz * 2); }
  127. /*
  128. #define BSR2_RET(pos, res) { res = (pos < (1 << (kNumLogBits + 6))) ? \
  129. p->g_FastPos[pos >> 6] + 12 : \
  130. p->g_FastPos[pos >> (6 + kNumLogBits - 1)] + (6 + (kNumLogBits - 1)) * 2; }
  131. */
  132. #define GetPosSlot1(pos) p->g_FastPos[pos]
  133. #define GetPosSlot2(pos, res) { BSR2_RET(pos, res); }
  134. #define GetPosSlot(pos, res) { if (pos < kNumFullDistances) res = p->g_FastPos[pos]; else BSR2_RET(pos, res); }
  135. #endif
  136. #define LZMA_NUM_REPS 4
  137. typedef unsigned CState;
  138. typedef struct
  139. {
  140. UInt32 price;
  141. CState state;
  142. int prev1IsChar;
  143. int prev2;
  144. UInt32 posPrev2;
  145. UInt32 backPrev2;
  146. UInt32 posPrev;
  147. UInt32 backPrev;
  148. UInt32 backs[LZMA_NUM_REPS];
  149. } COptimal;
  150. #define kNumOpts (1 << 12)
  151. #define kNumLenToPosStates 4
  152. #define kNumPosSlotBits 6
  153. #define kDicLogSizeMin 0
  154. #define kDicLogSizeMax 32
  155. #define kDistTableSizeMax (kDicLogSizeMax * 2)
  156. #define kNumAlignBits 4
  157. #define kAlignTableSize (1 << kNumAlignBits)
  158. #define kAlignMask (kAlignTableSize - 1)
  159. #define kStartPosModelIndex 4
  160. #define kEndPosModelIndex 14
  161. #define kNumPosModels (kEndPosModelIndex - kStartPosModelIndex)
  162. #define kNumFullDistances (1 << (kEndPosModelIndex >> 1))
  163. #ifdef _LZMA_PROB32
  164. #define CLzmaProb UInt32
  165. #else
  166. #define CLzmaProb UInt16
  167. #endif
  168. #define LZMA_PB_MAX 4
  169. #define LZMA_LC_MAX 8
  170. #define LZMA_LP_MAX 4
  171. #define LZMA_NUM_PB_STATES_MAX (1 << LZMA_PB_MAX)
  172. #define kLenNumLowBits 3
  173. #define kLenNumLowSymbols (1 << kLenNumLowBits)
  174. #define kLenNumMidBits 3
  175. #define kLenNumMidSymbols (1 << kLenNumMidBits)
  176. #define kLenNumHighBits 8
  177. #define kLenNumHighSymbols (1 << kLenNumHighBits)
  178. #define kLenNumSymbolsTotal (kLenNumLowSymbols + kLenNumMidSymbols + kLenNumHighSymbols)
  179. #define LZMA_MATCH_LEN_MIN 2
  180. #define LZMA_MATCH_LEN_MAX (LZMA_MATCH_LEN_MIN + kLenNumSymbolsTotal - 1)
  181. #define kNumStates 12
  182. typedef struct
  183. {
  184. CLzmaProb choice;
  185. CLzmaProb choice2;
  186. CLzmaProb low[LZMA_NUM_PB_STATES_MAX << kLenNumLowBits];
  187. CLzmaProb mid[LZMA_NUM_PB_STATES_MAX << kLenNumMidBits];
  188. CLzmaProb high[kLenNumHighSymbols];
  189. } CLenEnc;
  190. typedef struct
  191. {
  192. CLenEnc p;
  193. UInt32 tableSize;
  194. UInt32 prices[LZMA_NUM_PB_STATES_MAX][kLenNumSymbolsTotal];
  195. UInt32 counters[LZMA_NUM_PB_STATES_MAX];
  196. } CLenPriceEnc;
  197. typedef struct
  198. {
  199. UInt32 range;
  200. Byte cache;
  201. UInt64 low;
  202. UInt64 cacheSize;
  203. Byte *buf;
  204. Byte *bufLim;
  205. Byte *bufBase;
  206. ISeqOutStream *outStream;
  207. UInt64 processed;
  208. SRes res;
  209. } CRangeEnc;
  210. typedef struct
  211. {
  212. CLzmaProb *litProbs;
  213. UInt32 state;
  214. UInt32 reps[LZMA_NUM_REPS];
  215. CLzmaProb isMatch[kNumStates][LZMA_NUM_PB_STATES_MAX];
  216. CLzmaProb isRep[kNumStates];
  217. CLzmaProb isRepG0[kNumStates];
  218. CLzmaProb isRepG1[kNumStates];
  219. CLzmaProb isRepG2[kNumStates];
  220. CLzmaProb isRep0Long[kNumStates][LZMA_NUM_PB_STATES_MAX];
  221. CLzmaProb posSlotEncoder[kNumLenToPosStates][1 << kNumPosSlotBits];
  222. CLzmaProb posEncoders[kNumFullDistances - kEndPosModelIndex];
  223. CLzmaProb posAlignEncoder[1 << kNumAlignBits];
  224. CLenPriceEnc lenEnc;
  225. CLenPriceEnc repLenEnc;
  226. } CSaveState;
  227. typedef struct
  228. {
  229. void *matchFinderObj;
  230. IMatchFinder matchFinder;
  231. UInt32 optimumEndIndex;
  232. UInt32 optimumCurrentIndex;
  233. UInt32 longestMatchLength;
  234. UInt32 numPairs;
  235. UInt32 numAvail;
  236. UInt32 numFastBytes;
  237. UInt32 additionalOffset;
  238. UInt32 reps[LZMA_NUM_REPS];
  239. UInt32 state;
  240. unsigned lc, lp, pb;
  241. unsigned lpMask, pbMask;
  242. unsigned lclp;
  243. CLzmaProb *litProbs;
  244. Bool fastMode;
  245. Bool writeEndMark;
  246. Bool finished;
  247. Bool multiThread;
  248. Bool needInit;
  249. UInt64 nowPos64;
  250. UInt32 matchPriceCount;
  251. UInt32 alignPriceCount;
  252. UInt32 distTableSize;
  253. UInt32 dictSize;
  254. SRes result;
  255. CRangeEnc rc;
  256. #ifndef _7ZIP_ST
  257. Bool mtMode;
  258. CMatchFinderMt matchFinderMt;
  259. #endif
  260. CMatchFinder matchFinderBase;
  261. #ifndef _7ZIP_ST
  262. Byte pad[128];
  263. #endif
  264. COptimal opt[kNumOpts];
  265. #ifndef LZMA_LOG_BSR
  266. Byte g_FastPos[1 << kNumLogBits];
  267. #endif
  268. UInt32 ProbPrices[kBitModelTotal >> kNumMoveReducingBits];
  269. UInt32 matches[LZMA_MATCH_LEN_MAX * 2 + 2 + 1];
  270. UInt32 posSlotPrices[kNumLenToPosStates][kDistTableSizeMax];
  271. UInt32 distancesPrices[kNumLenToPosStates][kNumFullDistances];
  272. UInt32 alignPrices[kAlignTableSize];
  273. CLzmaProb isMatch[kNumStates][LZMA_NUM_PB_STATES_MAX];
  274. CLzmaProb isRep[kNumStates];
  275. CLzmaProb isRepG0[kNumStates];
  276. CLzmaProb isRepG1[kNumStates];
  277. CLzmaProb isRepG2[kNumStates];
  278. CLzmaProb isRep0Long[kNumStates][LZMA_NUM_PB_STATES_MAX];
  279. CLzmaProb posSlotEncoder[kNumLenToPosStates][1 << kNumPosSlotBits];
  280. CLzmaProb posEncoders[kNumFullDistances - kEndPosModelIndex];
  281. CLzmaProb posAlignEncoder[1 << kNumAlignBits];
  282. CLenPriceEnc lenEnc;
  283. CLenPriceEnc repLenEnc;
  284. CSaveState saveState;
  285. #ifndef _7ZIP_ST
  286. Byte pad2[128];
  287. #endif
  288. } CLzmaEnc;
  289. void LzmaEnc_SaveState(CLzmaEncHandle pp)
  290. {
  291. CLzmaEnc *p = (CLzmaEnc *)pp;
  292. CSaveState *dest = &p->saveState;
  293. int i;
  294. dest->lenEnc = p->lenEnc;
  295. dest->repLenEnc = p->repLenEnc;
  296. dest->state = p->state;
  297. for (i = 0; i < kNumStates; i++)
  298. {
  299. memcpy(dest->isMatch[i], p->isMatch[i], sizeof(p->isMatch[i]));
  300. memcpy(dest->isRep0Long[i], p->isRep0Long[i], sizeof(p->isRep0Long[i]));
  301. }
  302. for (i = 0; i < kNumLenToPosStates; i++)
  303. memcpy(dest->posSlotEncoder[i], p->posSlotEncoder[i], sizeof(p->posSlotEncoder[i]));
  304. memcpy(dest->isRep, p->isRep, sizeof(p->isRep));
  305. memcpy(dest->isRepG0, p->isRepG0, sizeof(p->isRepG0));
  306. memcpy(dest->isRepG1, p->isRepG1, sizeof(p->isRepG1));
  307. memcpy(dest->isRepG2, p->isRepG2, sizeof(p->isRepG2));
  308. memcpy(dest->posEncoders, p->posEncoders, sizeof(p->posEncoders));
  309. memcpy(dest->posAlignEncoder, p->posAlignEncoder, sizeof(p->posAlignEncoder));
  310. memcpy(dest->reps, p->reps, sizeof(p->reps));
  311. memcpy(dest->litProbs, p->litProbs, ((UInt32)0x300 << p->lclp) * sizeof(CLzmaProb));
  312. }
  313. void LzmaEnc_RestoreState(CLzmaEncHandle pp)
  314. {
  315. CLzmaEnc *dest = (CLzmaEnc *)pp;
  316. const CSaveState *p = &dest->saveState;
  317. int i;
  318. dest->lenEnc = p->lenEnc;
  319. dest->repLenEnc = p->repLenEnc;
  320. dest->state = p->state;
  321. for (i = 0; i < kNumStates; i++)
  322. {
  323. memcpy(dest->isMatch[i], p->isMatch[i], sizeof(p->isMatch[i]));
  324. memcpy(dest->isRep0Long[i], p->isRep0Long[i], sizeof(p->isRep0Long[i]));
  325. }
  326. for (i = 0; i < kNumLenToPosStates; i++)
  327. memcpy(dest->posSlotEncoder[i], p->posSlotEncoder[i], sizeof(p->posSlotEncoder[i]));
  328. memcpy(dest->isRep, p->isRep, sizeof(p->isRep));
  329. memcpy(dest->isRepG0, p->isRepG0, sizeof(p->isRepG0));
  330. memcpy(dest->isRepG1, p->isRepG1, sizeof(p->isRepG1));
  331. memcpy(dest->isRepG2, p->isRepG2, sizeof(p->isRepG2));
  332. memcpy(dest->posEncoders, p->posEncoders, sizeof(p->posEncoders));
  333. memcpy(dest->posAlignEncoder, p->posAlignEncoder, sizeof(p->posAlignEncoder));
  334. memcpy(dest->reps, p->reps, sizeof(p->reps));
  335. memcpy(dest->litProbs, p->litProbs, ((UInt32)0x300 << dest->lclp) * sizeof(CLzmaProb));
  336. }
  337. SRes LzmaEnc_SetProps(CLzmaEncHandle pp, const CLzmaEncProps *props2)
  338. {
  339. CLzmaEnc *p = (CLzmaEnc *)pp;
  340. CLzmaEncProps props = *props2;
  341. LzmaEncProps_Normalize(&props);
  342. if (props.lc > LZMA_LC_MAX
  343. || props.lp > LZMA_LP_MAX
  344. || props.pb > LZMA_PB_MAX
  345. || props.dictSize > ((UInt64)1 << kDicLogSizeMaxCompress)
  346. || props.dictSize > kMaxHistorySize)
  347. return SZ_ERROR_PARAM;
  348. p->dictSize = props.dictSize;
  349. {
  350. unsigned fb = props.fb;
  351. if (fb < 5)
  352. fb = 5;
  353. if (fb > LZMA_MATCH_LEN_MAX)
  354. fb = LZMA_MATCH_LEN_MAX;
  355. p->numFastBytes = fb;
  356. }
  357. p->lc = props.lc;
  358. p->lp = props.lp;
  359. p->pb = props.pb;
  360. p->fastMode = (props.algo == 0);
  361. p->matchFinderBase.btMode = (Byte)(props.btMode ? 1 : 0);
  362. {
  363. UInt32 numHashBytes = 4;
  364. if (props.btMode)
  365. {
  366. if (props.numHashBytes < 2)
  367. numHashBytes = 2;
  368. else if (props.numHashBytes < 4)
  369. numHashBytes = props.numHashBytes;
  370. }
  371. p->matchFinderBase.numHashBytes = numHashBytes;
  372. }
  373. p->matchFinderBase.cutValue = props.mc;
  374. p->writeEndMark = props.writeEndMark;
  375. #ifndef _7ZIP_ST
  376. /*
  377. if (newMultiThread != _multiThread)
  378. {
  379. ReleaseMatchFinder();
  380. _multiThread = newMultiThread;
  381. }
  382. */
  383. p->multiThread = (props.numThreads > 1);
  384. #endif
  385. return SZ_OK;
  386. }
  387. static const int kLiteralNextStates[kNumStates] = {0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 4, 5};
  388. static const int kMatchNextStates[kNumStates] = {7, 7, 7, 7, 7, 7, 7, 10, 10, 10, 10, 10};
  389. static const int kRepNextStates[kNumStates] = {8, 8, 8, 8, 8, 8, 8, 11, 11, 11, 11, 11};
  390. static const int kShortRepNextStates[kNumStates]= {9, 9, 9, 9, 9, 9, 9, 11, 11, 11, 11, 11};
  391. #define IsCharState(s) ((s) < 7)
  392. #define GetLenToPosState(len) (((len) < kNumLenToPosStates + 1) ? (len) - 2 : kNumLenToPosStates - 1)
  393. #define kInfinityPrice (1 << 30)
  394. static void RangeEnc_Construct(CRangeEnc *p)
  395. {
  396. p->outStream = NULL;
  397. p->bufBase = NULL;
  398. }
  399. #define RangeEnc_GetProcessed(p) ((p)->processed + ((p)->buf - (p)->bufBase) + (p)->cacheSize)
  400. #define RC_BUF_SIZE (1 << 16)
  401. static int RangeEnc_Alloc(CRangeEnc *p, ISzAllocPtr alloc)
  402. {
  403. if (!p->bufBase)
  404. {
  405. p->bufBase = (Byte *)ISzAlloc_Alloc(alloc, RC_BUF_SIZE);
  406. if (!p->bufBase)
  407. return 0;
  408. p->bufLim = p->bufBase + RC_BUF_SIZE;
  409. }
  410. return 1;
  411. }
  412. static void RangeEnc_Free(CRangeEnc *p, ISzAllocPtr alloc)
  413. {
  414. ISzAlloc_Free(alloc, p->bufBase);
  415. p->bufBase = 0;
  416. }
  417. static void RangeEnc_Init(CRangeEnc *p)
  418. {
  419. /* Stream.Init(); */
  420. p->low = 0;
  421. p->range = 0xFFFFFFFF;
  422. p->cacheSize = 1;
  423. p->cache = 0;
  424. p->buf = p->bufBase;
  425. p->processed = 0;
  426. p->res = SZ_OK;
  427. }
  428. static void RangeEnc_FlushStream(CRangeEnc *p)
  429. {
  430. size_t num;
  431. if (p->res != SZ_OK)
  432. return;
  433. num = p->buf - p->bufBase;
  434. if (num != ISeqOutStream_Write(p->outStream, p->bufBase, num))
  435. p->res = SZ_ERROR_WRITE;
  436. p->processed += num;
  437. p->buf = p->bufBase;
  438. }
  439. static void MY_FAST_CALL RangeEnc_ShiftLow(CRangeEnc *p)
  440. {
  441. if ((UInt32)p->low < (UInt32)0xFF000000 || (unsigned)(p->low >> 32) != 0)
  442. {
  443. Byte temp = p->cache;
  444. do
  445. {
  446. Byte *buf = p->buf;
  447. *buf++ = (Byte)(temp + (Byte)(p->low >> 32));
  448. p->buf = buf;
  449. if (buf == p->bufLim)
  450. RangeEnc_FlushStream(p);
  451. temp = 0xFF;
  452. }
  453. while (--p->cacheSize != 0);
  454. p->cache = (Byte)((UInt32)p->low >> 24);
  455. }
  456. p->cacheSize++;
  457. p->low = (UInt32)p->low << 8;
  458. }
  459. static void RangeEnc_FlushData(CRangeEnc *p)
  460. {
  461. int i;
  462. for (i = 0; i < 5; i++)
  463. RangeEnc_ShiftLow(p);
  464. }
  465. static void RangeEnc_EncodeDirectBits(CRangeEnc *p, UInt32 value, unsigned numBits)
  466. {
  467. do
  468. {
  469. p->range >>= 1;
  470. p->low += p->range & (0 - ((value >> --numBits) & 1));
  471. if (p->range < kTopValue)
  472. {
  473. p->range <<= 8;
  474. RangeEnc_ShiftLow(p);
  475. }
  476. }
  477. while (numBits != 0);
  478. }
  479. static void RangeEnc_EncodeBit(CRangeEnc *p, CLzmaProb *prob, UInt32 symbol)
  480. {
  481. UInt32 ttt = *prob;
  482. UInt32 newBound = (p->range >> kNumBitModelTotalBits) * ttt;
  483. if (symbol == 0)
  484. {
  485. p->range = newBound;
  486. ttt += (kBitModelTotal - ttt) >> kNumMoveBits;
  487. }
  488. else
  489. {
  490. p->low += newBound;
  491. p->range -= newBound;
  492. ttt -= ttt >> kNumMoveBits;
  493. }
  494. *prob = (CLzmaProb)ttt;
  495. if (p->range < kTopValue)
  496. {
  497. p->range <<= 8;
  498. RangeEnc_ShiftLow(p);
  499. }
  500. }
  501. static void LitEnc_Encode(CRangeEnc *p, CLzmaProb *probs, UInt32 symbol)
  502. {
  503. symbol |= 0x100;
  504. do
  505. {
  506. RangeEnc_EncodeBit(p, probs + (symbol >> 8), (symbol >> 7) & 1);
  507. symbol <<= 1;
  508. }
  509. while (symbol < 0x10000);
  510. }
  511. static void LitEnc_EncodeMatched(CRangeEnc *p, CLzmaProb *probs, UInt32 symbol, UInt32 matchByte)
  512. {
  513. UInt32 offs = 0x100;
  514. symbol |= 0x100;
  515. do
  516. {
  517. matchByte <<= 1;
  518. RangeEnc_EncodeBit(p, probs + (offs + (matchByte & offs) + (symbol >> 8)), (symbol >> 7) & 1);
  519. symbol <<= 1;
  520. offs &= ~(matchByte ^ symbol);
  521. }
  522. while (symbol < 0x10000);
  523. }
  524. static void LzmaEnc_InitPriceTables(UInt32 *ProbPrices)
  525. {
  526. UInt32 i;
  527. for (i = (1 << kNumMoveReducingBits) / 2; i < kBitModelTotal; i += (1 << kNumMoveReducingBits))
  528. {
  529. const int kCyclesBits = kNumBitPriceShiftBits;
  530. UInt32 w = i;
  531. UInt32 bitCount = 0;
  532. int j;
  533. for (j = 0; j < kCyclesBits; j++)
  534. {
  535. w = w * w;
  536. bitCount <<= 1;
  537. while (w >= ((UInt32)1 << 16))
  538. {
  539. w >>= 1;
  540. bitCount++;
  541. }
  542. }
  543. ProbPrices[i >> kNumMoveReducingBits] = ((kNumBitModelTotalBits << kCyclesBits) - 15 - bitCount);
  544. }
  545. }
  546. #define GET_PRICE(prob, symbol) \
  547. p->ProbPrices[((prob) ^ (((-(int)(symbol))) & (kBitModelTotal - 1))) >> kNumMoveReducingBits];
  548. #define GET_PRICEa(prob, symbol) \
  549. ProbPrices[((prob) ^ ((-((int)(symbol))) & (kBitModelTotal - 1))) >> kNumMoveReducingBits];
  550. #define GET_PRICE_0(prob) p->ProbPrices[(prob) >> kNumMoveReducingBits]
  551. #define GET_PRICE_1(prob) p->ProbPrices[((prob) ^ (kBitModelTotal - 1)) >> kNumMoveReducingBits]
  552. #define GET_PRICE_0a(prob) ProbPrices[(prob) >> kNumMoveReducingBits]
  553. #define GET_PRICE_1a(prob) ProbPrices[((prob) ^ (kBitModelTotal - 1)) >> kNumMoveReducingBits]
  554. static UInt32 LitEnc_GetPrice(const CLzmaProb *probs, UInt32 symbol, const UInt32 *ProbPrices)
  555. {
  556. UInt32 price = 0;
  557. symbol |= 0x100;
  558. do
  559. {
  560. price += GET_PRICEa(probs[symbol >> 8], (symbol >> 7) & 1);
  561. symbol <<= 1;
  562. }
  563. while (symbol < 0x10000);
  564. return price;
  565. }
  566. static UInt32 LitEnc_GetPriceMatched(const CLzmaProb *probs, UInt32 symbol, UInt32 matchByte, const UInt32 *ProbPrices)
  567. {
  568. UInt32 price = 0;
  569. UInt32 offs = 0x100;
  570. symbol |= 0x100;
  571. do
  572. {
  573. matchByte <<= 1;
  574. price += GET_PRICEa(probs[offs + (matchByte & offs) + (symbol >> 8)], (symbol >> 7) & 1);
  575. symbol <<= 1;
  576. offs &= ~(matchByte ^ symbol);
  577. }
  578. while (symbol < 0x10000);
  579. return price;
  580. }
  581. static void RcTree_Encode(CRangeEnc *rc, CLzmaProb *probs, int numBitLevels, UInt32 symbol)
  582. {
  583. UInt32 m = 1;
  584. int i;
  585. for (i = numBitLevels; i != 0;)
  586. {
  587. UInt32 bit;
  588. i--;
  589. bit = (symbol >> i) & 1;
  590. RangeEnc_EncodeBit(rc, probs + m, bit);
  591. m = (m << 1) | bit;
  592. }
  593. }
  594. static void RcTree_ReverseEncode(CRangeEnc *rc, CLzmaProb *probs, int numBitLevels, UInt32 symbol)
  595. {
  596. UInt32 m = 1;
  597. int i;
  598. for (i = 0; i < numBitLevels; i++)
  599. {
  600. UInt32 bit = symbol & 1;
  601. RangeEnc_EncodeBit(rc, probs + m, bit);
  602. m = (m << 1) | bit;
  603. symbol >>= 1;
  604. }
  605. }
  606. static UInt32 RcTree_GetPrice(const CLzmaProb *probs, int numBitLevels, UInt32 symbol, const UInt32 *ProbPrices)
  607. {
  608. UInt32 price = 0;
  609. symbol |= (1 << numBitLevels);
  610. while (symbol != 1)
  611. {
  612. price += GET_PRICEa(probs[symbol >> 1], symbol & 1);
  613. symbol >>= 1;
  614. }
  615. return price;
  616. }
  617. static UInt32 RcTree_ReverseGetPrice(const CLzmaProb *probs, int numBitLevels, UInt32 symbol, const UInt32 *ProbPrices)
  618. {
  619. UInt32 price = 0;
  620. UInt32 m = 1;
  621. int i;
  622. for (i = numBitLevels; i != 0; i--)
  623. {
  624. UInt32 bit = symbol & 1;
  625. symbol >>= 1;
  626. price += GET_PRICEa(probs[m], bit);
  627. m = (m << 1) | bit;
  628. }
  629. return price;
  630. }
  631. static void LenEnc_Init(CLenEnc *p)
  632. {
  633. unsigned i;
  634. p->choice = p->choice2 = kProbInitValue;
  635. for (i = 0; i < (LZMA_NUM_PB_STATES_MAX << kLenNumLowBits); i++)
  636. p->low[i] = kProbInitValue;
  637. for (i = 0; i < (LZMA_NUM_PB_STATES_MAX << kLenNumMidBits); i++)
  638. p->mid[i] = kProbInitValue;
  639. for (i = 0; i < kLenNumHighSymbols; i++)
  640. p->high[i] = kProbInitValue;
  641. }
  642. static void LenEnc_Encode(CLenEnc *p, CRangeEnc *rc, UInt32 symbol, UInt32 posState)
  643. {
  644. if (symbol < kLenNumLowSymbols)
  645. {
  646. RangeEnc_EncodeBit(rc, &p->choice, 0);
  647. RcTree_Encode(rc, p->low + (posState << kLenNumLowBits), kLenNumLowBits, symbol);
  648. }
  649. else
  650. {
  651. RangeEnc_EncodeBit(rc, &p->choice, 1);
  652. if (symbol < kLenNumLowSymbols + kLenNumMidSymbols)
  653. {
  654. RangeEnc_EncodeBit(rc, &p->choice2, 0);
  655. RcTree_Encode(rc, p->mid + (posState << kLenNumMidBits), kLenNumMidBits, symbol - kLenNumLowSymbols);
  656. }
  657. else
  658. {
  659. RangeEnc_EncodeBit(rc, &p->choice2, 1);
  660. RcTree_Encode(rc, p->high, kLenNumHighBits, symbol - kLenNumLowSymbols - kLenNumMidSymbols);
  661. }
  662. }
  663. }
  664. static void LenEnc_SetPrices(CLenEnc *p, UInt32 posState, UInt32 numSymbols, UInt32 *prices, const UInt32 *ProbPrices)
  665. {
  666. UInt32 a0 = GET_PRICE_0a(p->choice);
  667. UInt32 a1 = GET_PRICE_1a(p->choice);
  668. UInt32 b0 = a1 + GET_PRICE_0a(p->choice2);
  669. UInt32 b1 = a1 + GET_PRICE_1a(p->choice2);
  670. UInt32 i = 0;
  671. for (i = 0; i < kLenNumLowSymbols; i++)
  672. {
  673. if (i >= numSymbols)
  674. return;
  675. prices[i] = a0 + RcTree_GetPrice(p->low + (posState << kLenNumLowBits), kLenNumLowBits, i, ProbPrices);
  676. }
  677. for (; i < kLenNumLowSymbols + kLenNumMidSymbols; i++)
  678. {
  679. if (i >= numSymbols)
  680. return;
  681. prices[i] = b0 + RcTree_GetPrice(p->mid + (posState << kLenNumMidBits), kLenNumMidBits, i - kLenNumLowSymbols, ProbPrices);
  682. }
  683. for (; i < numSymbols; i++)
  684. prices[i] = b1 + RcTree_GetPrice(p->high, kLenNumHighBits, i - kLenNumLowSymbols - kLenNumMidSymbols, ProbPrices);
  685. }
  686. static void MY_FAST_CALL LenPriceEnc_UpdateTable(CLenPriceEnc *p, UInt32 posState, const UInt32 *ProbPrices)
  687. {
  688. LenEnc_SetPrices(&p->p, posState, p->tableSize, p->prices[posState], ProbPrices);
  689. p->counters[posState] = p->tableSize;
  690. }
  691. static void LenPriceEnc_UpdateTables(CLenPriceEnc *p, UInt32 numPosStates, const UInt32 *ProbPrices)
  692. {
  693. UInt32 posState;
  694. for (posState = 0; posState < numPosStates; posState++)
  695. LenPriceEnc_UpdateTable(p, posState, ProbPrices);
  696. }
  697. static void LenEnc_Encode2(CLenPriceEnc *p, CRangeEnc *rc, UInt32 symbol, UInt32 posState, Bool updatePrice, const UInt32 *ProbPrices)
  698. {
  699. LenEnc_Encode(&p->p, rc, symbol, posState);
  700. if (updatePrice)
  701. if (--p->counters[posState] == 0)
  702. LenPriceEnc_UpdateTable(p, posState, ProbPrices);
  703. }
  704. static void MovePos(CLzmaEnc *p, UInt32 num)
  705. {
  706. #ifdef SHOW_STAT
  707. g_STAT_OFFSET += num;
  708. printf("\n MovePos %u", num);
  709. #endif
  710. if (num != 0)
  711. {
  712. p->additionalOffset += num;
  713. p->matchFinder.Skip(p->matchFinderObj, num);
  714. }
  715. }
  716. static UInt32 ReadMatchDistances(CLzmaEnc *p, UInt32 *numDistancePairsRes)
  717. {
  718. UInt32 lenRes = 0, numPairs;
  719. p->numAvail = p->matchFinder.GetNumAvailableBytes(p->matchFinderObj);
  720. numPairs = p->matchFinder.GetMatches(p->matchFinderObj, p->matches);
  721. #ifdef SHOW_STAT
  722. printf("\n i = %u numPairs = %u ", g_STAT_OFFSET, numPairs / 2);
  723. g_STAT_OFFSET++;
  724. {
  725. UInt32 i;
  726. for (i = 0; i < numPairs; i += 2)
  727. printf("%2u %6u | ", p->matches[i], p->matches[i + 1]);
  728. }
  729. #endif
  730. if (numPairs > 0)
  731. {
  732. lenRes = p->matches[(size_t)numPairs - 2];
  733. if (lenRes == p->numFastBytes)
  734. {
  735. UInt32 numAvail = p->numAvail;
  736. if (numAvail > LZMA_MATCH_LEN_MAX)
  737. numAvail = LZMA_MATCH_LEN_MAX;
  738. {
  739. const Byte *pbyCur = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - 1;
  740. const Byte *pby = pbyCur + lenRes;
  741. ptrdiff_t dif = (ptrdiff_t)-1 - p->matches[(size_t)numPairs - 1];
  742. const Byte *pbyLim = pbyCur + numAvail;
  743. for (; pby != pbyLim && *pby == pby[dif]; pby++);
  744. lenRes = (UInt32)(pby - pbyCur);
  745. }
  746. }
  747. }
  748. p->additionalOffset++;
  749. *numDistancePairsRes = numPairs;
  750. return lenRes;
  751. }
  752. #define MakeAsChar(p) (p)->backPrev = (UInt32)(-1); (p)->prev1IsChar = False;
  753. #define MakeAsShortRep(p) (p)->backPrev = 0; (p)->prev1IsChar = False;
  754. #define IsShortRep(p) ((p)->backPrev == 0)
  755. static UInt32 GetRepLen1Price(CLzmaEnc *p, UInt32 state, UInt32 posState)
  756. {
  757. return
  758. GET_PRICE_0(p->isRepG0[state]) +
  759. GET_PRICE_0(p->isRep0Long[state][posState]);
  760. }
  761. static UInt32 GetPureRepPrice(CLzmaEnc *p, UInt32 repIndex, UInt32 state, UInt32 posState)
  762. {
  763. UInt32 price;
  764. if (repIndex == 0)
  765. {
  766. price = GET_PRICE_0(p->isRepG0[state]);
  767. price += GET_PRICE_1(p->isRep0Long[state][posState]);
  768. }
  769. else
  770. {
  771. price = GET_PRICE_1(p->isRepG0[state]);
  772. if (repIndex == 1)
  773. price += GET_PRICE_0(p->isRepG1[state]);
  774. else
  775. {
  776. price += GET_PRICE_1(p->isRepG1[state]);
  777. price += GET_PRICE(p->isRepG2[state], repIndex - 2);
  778. }
  779. }
  780. return price;
  781. }
  782. static UInt32 GetRepPrice(CLzmaEnc *p, UInt32 repIndex, UInt32 len, UInt32 state, UInt32 posState)
  783. {
  784. return p->repLenEnc.prices[posState][(size_t)len - LZMA_MATCH_LEN_MIN] +
  785. GetPureRepPrice(p, repIndex, state, posState);
  786. }
  787. static UInt32 Backward(CLzmaEnc *p, UInt32 *backRes, UInt32 cur)
  788. {
  789. UInt32 posMem = p->opt[cur].posPrev;
  790. UInt32 backMem = p->opt[cur].backPrev;
  791. p->optimumEndIndex = cur;
  792. do
  793. {
  794. if (p->opt[cur].prev1IsChar)
  795. {
  796. MakeAsChar(&p->opt[posMem])
  797. p->opt[posMem].posPrev = posMem - 1;
  798. if (p->opt[cur].prev2)
  799. {
  800. p->opt[(size_t)posMem - 1].prev1IsChar = False;
  801. p->opt[(size_t)posMem - 1].posPrev = p->opt[cur].posPrev2;
  802. p->opt[(size_t)posMem - 1].backPrev = p->opt[cur].backPrev2;
  803. }
  804. }
  805. {
  806. UInt32 posPrev = posMem;
  807. UInt32 backCur = backMem;
  808. backMem = p->opt[posPrev].backPrev;
  809. posMem = p->opt[posPrev].posPrev;
  810. p->opt[posPrev].backPrev = backCur;
  811. p->opt[posPrev].posPrev = cur;
  812. cur = posPrev;
  813. }
  814. }
  815. while (cur != 0);
  816. *backRes = p->opt[0].backPrev;
  817. p->optimumCurrentIndex = p->opt[0].posPrev;
  818. return p->optimumCurrentIndex;
  819. }
  820. #define LIT_PROBS(pos, prevByte) (p->litProbs + ((((pos) & p->lpMask) << p->lc) + ((prevByte) >> (8 - p->lc))) * (UInt32)0x300)
  821. static UInt32 GetOptimum(CLzmaEnc *p, UInt32 position, UInt32 *backRes)
  822. {
  823. UInt32 lenEnd, cur;
  824. UInt32 reps[LZMA_NUM_REPS], repLens[LZMA_NUM_REPS];
  825. UInt32 *matches;
  826. {
  827. UInt32 numAvail, mainLen, numPairs, repMaxIndex, i, posState, len;
  828. UInt32 matchPrice, repMatchPrice, normalMatchPrice;
  829. const Byte *data;
  830. Byte curByte, matchByte;
  831. if (p->optimumEndIndex != p->optimumCurrentIndex)
  832. {
  833. const COptimal *opt = &p->opt[p->optimumCurrentIndex];
  834. UInt32 lenRes = opt->posPrev - p->optimumCurrentIndex;
  835. *backRes = opt->backPrev;
  836. p->optimumCurrentIndex = opt->posPrev;
  837. return lenRes;
  838. }
  839. p->optimumCurrentIndex = p->optimumEndIndex = 0;
  840. if (p->additionalOffset == 0)
  841. mainLen = ReadMatchDistances(p, &numPairs);
  842. else
  843. {
  844. mainLen = p->longestMatchLength;
  845. numPairs = p->numPairs;
  846. }
  847. numAvail = p->numAvail;
  848. if (numAvail < 2)
  849. {
  850. *backRes = (UInt32)(-1);
  851. return 1;
  852. }
  853. if (numAvail > LZMA_MATCH_LEN_MAX)
  854. numAvail = LZMA_MATCH_LEN_MAX;
  855. data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - 1;
  856. repMaxIndex = 0;
  857. for (i = 0; i < LZMA_NUM_REPS; i++)
  858. {
  859. UInt32 lenTest;
  860. const Byte *data2;
  861. reps[i] = p->reps[i];
  862. data2 = data - reps[i] - 1;
  863. if (data[0] != data2[0] || data[1] != data2[1])
  864. {
  865. repLens[i] = 0;
  866. continue;
  867. }
  868. for (lenTest = 2; lenTest < numAvail && data[lenTest] == data2[lenTest]; lenTest++);
  869. repLens[i] = lenTest;
  870. if (lenTest > repLens[repMaxIndex])
  871. repMaxIndex = i;
  872. }
  873. if (repLens[repMaxIndex] >= p->numFastBytes)
  874. {
  875. UInt32 lenRes;
  876. *backRes = repMaxIndex;
  877. lenRes = repLens[repMaxIndex];
  878. MovePos(p, lenRes - 1);
  879. return lenRes;
  880. }
  881. matches = p->matches;
  882. if (mainLen >= p->numFastBytes)
  883. {
  884. *backRes = matches[(size_t)numPairs - 1] + LZMA_NUM_REPS;
  885. MovePos(p, mainLen - 1);
  886. return mainLen;
  887. }
  888. curByte = *data;
  889. matchByte = *(data - (reps[0] + 1));
  890. if (mainLen < 2 && curByte != matchByte && repLens[repMaxIndex] < 2)
  891. {
  892. *backRes = (UInt32)-1;
  893. return 1;
  894. }
  895. p->opt[0].state = (CState)p->state;
  896. posState = (position & p->pbMask);
  897. {
  898. const CLzmaProb *probs = LIT_PROBS(position, *(data - 1));
  899. p->opt[1].price = GET_PRICE_0(p->isMatch[p->state][posState]) +
  900. (!IsCharState(p->state) ?
  901. LitEnc_GetPriceMatched(probs, curByte, matchByte, p->ProbPrices) :
  902. LitEnc_GetPrice(probs, curByte, p->ProbPrices));
  903. }
  904. MakeAsChar(&p->opt[1]);
  905. matchPrice = GET_PRICE_1(p->isMatch[p->state][posState]);
  906. repMatchPrice = matchPrice + GET_PRICE_1(p->isRep[p->state]);
  907. if (matchByte == curByte)
  908. {
  909. UInt32 shortRepPrice = repMatchPrice + GetRepLen1Price(p, p->state, posState);
  910. if (shortRepPrice < p->opt[1].price)
  911. {
  912. p->opt[1].price = shortRepPrice;
  913. MakeAsShortRep(&p->opt[1]);
  914. }
  915. }
  916. lenEnd = ((mainLen >= repLens[repMaxIndex]) ? mainLen : repLens[repMaxIndex]);
  917. if (lenEnd < 2)
  918. {
  919. *backRes = p->opt[1].backPrev;
  920. return 1;
  921. }
  922. p->opt[1].posPrev = 0;
  923. for (i = 0; i < LZMA_NUM_REPS; i++)
  924. p->opt[0].backs[i] = reps[i];
  925. len = lenEnd;
  926. do
  927. p->opt[len--].price = kInfinityPrice;
  928. while (len >= 2);
  929. for (i = 0; i < LZMA_NUM_REPS; i++)
  930. {
  931. UInt32 repLen = repLens[i];
  932. UInt32 price;
  933. if (repLen < 2)
  934. continue;
  935. price = repMatchPrice + GetPureRepPrice(p, i, p->state, posState);
  936. do
  937. {
  938. UInt32 curAndLenPrice = price + p->repLenEnc.prices[posState][(size_t)repLen - 2];
  939. COptimal *opt = &p->opt[repLen];
  940. if (curAndLenPrice < opt->price)
  941. {
  942. opt->price = curAndLenPrice;
  943. opt->posPrev = 0;
  944. opt->backPrev = i;
  945. opt->prev1IsChar = False;
  946. }
  947. }
  948. while (--repLen >= 2);
  949. }
  950. normalMatchPrice = matchPrice + GET_PRICE_0(p->isRep[p->state]);
  951. len = ((repLens[0] >= 2) ? repLens[0] + 1 : 2);
  952. if (len <= mainLen)
  953. {
  954. UInt32 offs = 0;
  955. while (len > matches[offs])
  956. offs += 2;
  957. for (; ; len++)
  958. {
  959. COptimal *opt;
  960. UInt32 distance = matches[(size_t)offs + 1];
  961. UInt32 curAndLenPrice = normalMatchPrice + p->lenEnc.prices[posState][(size_t)len - LZMA_MATCH_LEN_MIN];
  962. UInt32 lenToPosState = GetLenToPosState(len);
  963. if (distance < kNumFullDistances)
  964. curAndLenPrice += p->distancesPrices[lenToPosState][distance];
  965. else
  966. {
  967. UInt32 slot;
  968. GetPosSlot2(distance, slot);
  969. curAndLenPrice += p->alignPrices[distance & kAlignMask] + p->posSlotPrices[lenToPosState][slot];
  970. }
  971. opt = &p->opt[len];
  972. if (curAndLenPrice < opt->price)
  973. {
  974. opt->price = curAndLenPrice;
  975. opt->posPrev = 0;
  976. opt->backPrev = distance + LZMA_NUM_REPS;
  977. opt->prev1IsChar = False;
  978. }
  979. if (len == matches[offs])
  980. {
  981. offs += 2;
  982. if (offs == numPairs)
  983. break;
  984. }
  985. }
  986. }
  987. cur = 0;
  988. #ifdef SHOW_STAT2
  989. /* if (position >= 0) */
  990. {
  991. unsigned i;
  992. printf("\n pos = %4X", position);
  993. for (i = cur; i <= lenEnd; i++)
  994. printf("\nprice[%4X] = %u", position - cur + i, p->opt[i].price);
  995. }
  996. #endif
  997. }
  998. for (;;)
  999. {
  1000. UInt32 numAvail;
  1001. UInt32 numAvailFull, newLen, numPairs, posPrev, state, posState, startLen;
  1002. UInt32 curPrice, curAnd1Price, matchPrice, repMatchPrice;
  1003. Bool nextIsChar;
  1004. Byte curByte, matchByte;
  1005. const Byte *data;
  1006. COptimal *curOpt;
  1007. COptimal *nextOpt;
  1008. cur++;
  1009. if (cur == lenEnd)
  1010. return Backward(p, backRes, cur);
  1011. newLen = ReadMatchDistances(p, &numPairs);
  1012. if (newLen >= p->numFastBytes)
  1013. {
  1014. p->numPairs = numPairs;
  1015. p->longestMatchLength = newLen;
  1016. return Backward(p, backRes, cur);
  1017. }
  1018. position++;
  1019. curOpt = &p->opt[cur];
  1020. posPrev = curOpt->posPrev;
  1021. if (curOpt->prev1IsChar)
  1022. {
  1023. posPrev--;
  1024. if (curOpt->prev2)
  1025. {
  1026. state = p->opt[curOpt->posPrev2].state;
  1027. if (curOpt->backPrev2 < LZMA_NUM_REPS)
  1028. state = kRepNextStates[state];
  1029. else
  1030. state = kMatchNextStates[state];
  1031. }
  1032. else
  1033. state = p->opt[posPrev].state;
  1034. state = kLiteralNextStates[state];
  1035. }
  1036. else
  1037. state = p->opt[posPrev].state;
  1038. if (posPrev == cur - 1)
  1039. {
  1040. if (IsShortRep(curOpt))
  1041. state = kShortRepNextStates[state];
  1042. else
  1043. state = kLiteralNextStates[state];
  1044. }
  1045. else
  1046. {
  1047. UInt32 pos;
  1048. const COptimal *prevOpt;
  1049. if (curOpt->prev1IsChar && curOpt->prev2)
  1050. {
  1051. posPrev = curOpt->posPrev2;
  1052. pos = curOpt->backPrev2;
  1053. state = kRepNextStates[state];
  1054. }
  1055. else
  1056. {
  1057. pos = curOpt->backPrev;
  1058. if (pos < LZMA_NUM_REPS)
  1059. state = kRepNextStates[state];
  1060. else
  1061. state = kMatchNextStates[state];
  1062. }
  1063. prevOpt = &p->opt[posPrev];
  1064. if (pos < LZMA_NUM_REPS)
  1065. {
  1066. UInt32 i;
  1067. reps[0] = prevOpt->backs[pos];
  1068. for (i = 1; i <= pos; i++)
  1069. reps[i] = prevOpt->backs[(size_t)i - 1];
  1070. for (; i < LZMA_NUM_REPS; i++)
  1071. reps[i] = prevOpt->backs[i];
  1072. }
  1073. else
  1074. {
  1075. UInt32 i;
  1076. reps[0] = (pos - LZMA_NUM_REPS);
  1077. for (i = 1; i < LZMA_NUM_REPS; i++)
  1078. reps[i] = prevOpt->backs[(size_t)i - 1];
  1079. }
  1080. }
  1081. curOpt->state = (CState)state;
  1082. curOpt->backs[0] = reps[0];
  1083. curOpt->backs[1] = reps[1];
  1084. curOpt->backs[2] = reps[2];
  1085. curOpt->backs[3] = reps[3];
  1086. curPrice = curOpt->price;
  1087. nextIsChar = False;
  1088. data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - 1;
  1089. curByte = *data;
  1090. matchByte = *(data - (reps[0] + 1));
  1091. posState = (position & p->pbMask);
  1092. curAnd1Price = curPrice + GET_PRICE_0(p->isMatch[state][posState]);
  1093. {
  1094. const CLzmaProb *probs = LIT_PROBS(position, *(data - 1));
  1095. curAnd1Price +=
  1096. (!IsCharState(state) ?
  1097. LitEnc_GetPriceMatched(probs, curByte, matchByte, p->ProbPrices) :
  1098. LitEnc_GetPrice(probs, curByte, p->ProbPrices));
  1099. }
  1100. nextOpt = &p->opt[(size_t)cur + 1];
  1101. if (curAnd1Price < nextOpt->price)
  1102. {
  1103. nextOpt->price = curAnd1Price;
  1104. nextOpt->posPrev = cur;
  1105. MakeAsChar(nextOpt);
  1106. nextIsChar = True;
  1107. }
  1108. matchPrice = curPrice + GET_PRICE_1(p->isMatch[state][posState]);
  1109. repMatchPrice = matchPrice + GET_PRICE_1(p->isRep[state]);
  1110. if (matchByte == curByte && !(nextOpt->posPrev < cur && nextOpt->backPrev == 0))
  1111. {
  1112. UInt32 shortRepPrice = repMatchPrice + GetRepLen1Price(p, state, posState);
  1113. if (shortRepPrice <= nextOpt->price)
  1114. {
  1115. nextOpt->price = shortRepPrice;
  1116. nextOpt->posPrev = cur;
  1117. MakeAsShortRep(nextOpt);
  1118. nextIsChar = True;
  1119. }
  1120. }
  1121. numAvailFull = p->numAvail;
  1122. {
  1123. UInt32 temp = kNumOpts - 1 - cur;
  1124. if (temp < numAvailFull)
  1125. numAvailFull = temp;
  1126. }
  1127. if (numAvailFull < 2)
  1128. continue;
  1129. numAvail = (numAvailFull <= p->numFastBytes ? numAvailFull : p->numFastBytes);
  1130. if (!nextIsChar && matchByte != curByte) /* speed optimization */
  1131. {
  1132. /* try Literal + rep0 */
  1133. UInt32 temp;
  1134. UInt32 lenTest2;
  1135. const Byte *data2 = data - reps[0] - 1;
  1136. UInt32 limit = p->numFastBytes + 1;
  1137. if (limit > numAvailFull)
  1138. limit = numAvailFull;
  1139. for (temp = 1; temp < limit && data[temp] == data2[temp]; temp++);
  1140. lenTest2 = temp - 1;
  1141. if (lenTest2 >= 2)
  1142. {
  1143. UInt32 state2 = kLiteralNextStates[state];
  1144. UInt32 posStateNext = (position + 1) & p->pbMask;
  1145. UInt32 nextRepMatchPrice = curAnd1Price +
  1146. GET_PRICE_1(p->isMatch[state2][posStateNext]) +
  1147. GET_PRICE_1(p->isRep[state2]);
  1148. /* for (; lenTest2 >= 2; lenTest2--) */
  1149. {
  1150. UInt32 curAndLenPrice;
  1151. COptimal *opt;
  1152. UInt32 offset = cur + 1 + lenTest2;
  1153. while (lenEnd < offset)
  1154. p->opt[++lenEnd].price = kInfinityPrice;
  1155. curAndLenPrice = nextRepMatchPrice + GetRepPrice(p, 0, lenTest2, state2, posStateNext);
  1156. opt = &p->opt[offset];
  1157. if (curAndLenPrice < opt->price)
  1158. {
  1159. opt->price = curAndLenPrice;
  1160. opt->posPrev = cur + 1;
  1161. opt->backPrev = 0;
  1162. opt->prev1IsChar = True;
  1163. opt->prev2 = False;
  1164. }
  1165. }
  1166. }
  1167. }
  1168. startLen = 2; /* speed optimization */
  1169. {
  1170. UInt32 repIndex;
  1171. for (repIndex = 0; repIndex < LZMA_NUM_REPS; repIndex++)
  1172. {
  1173. UInt32 lenTest;
  1174. UInt32 lenTestTemp;
  1175. UInt32 price;
  1176. const Byte *data2 = data - reps[repIndex] - 1;
  1177. if (data[0] != data2[0] || data[1] != data2[1])
  1178. continue;
  1179. for (lenTest = 2; lenTest < numAvail && data[lenTest] == data2[lenTest]; lenTest++);
  1180. while (lenEnd < cur + lenTest)
  1181. p->opt[++lenEnd].price = kInfinityPrice;
  1182. lenTestTemp = lenTest;
  1183. price = repMatchPrice + GetPureRepPrice(p, repIndex, state, posState);
  1184. do
  1185. {
  1186. UInt32 curAndLenPrice = price + p->repLenEnc.prices[posState][(size_t)lenTest - 2];
  1187. COptimal *opt = &p->opt[cur + lenTest];
  1188. if (curAndLenPrice < opt->price)
  1189. {
  1190. opt->price = curAndLenPrice;
  1191. opt->posPrev = cur;
  1192. opt->backPrev = repIndex;
  1193. opt->prev1IsChar = False;
  1194. }
  1195. }
  1196. while (--lenTest >= 2);
  1197. lenTest = lenTestTemp;
  1198. if (repIndex == 0)
  1199. startLen = lenTest + 1;
  1200. /* if (_maxMode) */
  1201. {
  1202. UInt32 lenTest2 = lenTest + 1;
  1203. UInt32 limit = lenTest2 + p->numFastBytes;
  1204. if (limit > numAvailFull)
  1205. limit = numAvailFull;
  1206. for (; lenTest2 < limit && data[lenTest2] == data2[lenTest2]; lenTest2++);
  1207. lenTest2 -= lenTest + 1;
  1208. if (lenTest2 >= 2)
  1209. {
  1210. UInt32 nextRepMatchPrice;
  1211. UInt32 state2 = kRepNextStates[state];
  1212. UInt32 posStateNext = (position + lenTest) & p->pbMask;
  1213. UInt32 curAndLenCharPrice =
  1214. price + p->repLenEnc.prices[posState][(size_t)lenTest - 2] +
  1215. GET_PRICE_0(p->isMatch[state2][posStateNext]) +
  1216. LitEnc_GetPriceMatched(LIT_PROBS(position + lenTest, data[(size_t)lenTest - 1]),
  1217. data[lenTest], data2[lenTest], p->ProbPrices);
  1218. state2 = kLiteralNextStates[state2];
  1219. posStateNext = (position + lenTest + 1) & p->pbMask;
  1220. nextRepMatchPrice = curAndLenCharPrice +
  1221. GET_PRICE_1(p->isMatch[state2][posStateNext]) +
  1222. GET_PRICE_1(p->isRep[state2]);
  1223. /* for (; lenTest2 >= 2; lenTest2--) */
  1224. {
  1225. UInt32 curAndLenPrice;
  1226. COptimal *opt;
  1227. UInt32 offset = cur + lenTest + 1 + lenTest2;
  1228. while (lenEnd < offset)
  1229. p->opt[++lenEnd].price = kInfinityPrice;
  1230. curAndLenPrice = nextRepMatchPrice + GetRepPrice(p, 0, lenTest2, state2, posStateNext);
  1231. opt = &p->opt[offset];
  1232. if (curAndLenPrice < opt->price)
  1233. {
  1234. opt->price = curAndLenPrice;
  1235. opt->posPrev = cur + lenTest + 1;
  1236. opt->backPrev = 0;
  1237. opt->prev1IsChar = True;
  1238. opt->prev2 = True;
  1239. opt->posPrev2 = cur;
  1240. opt->backPrev2 = repIndex;
  1241. }
  1242. }
  1243. }
  1244. }
  1245. }
  1246. }
  1247. /* for (UInt32 lenTest = 2; lenTest <= newLen; lenTest++) */
  1248. if (newLen > numAvail)
  1249. {
  1250. newLen = numAvail;
  1251. for (numPairs = 0; newLen > matches[numPairs]; numPairs += 2);
  1252. matches[numPairs] = newLen;
  1253. numPairs += 2;
  1254. }
  1255. if (newLen >= startLen)
  1256. {
  1257. UInt32 normalMatchPrice = matchPrice + GET_PRICE_0(p->isRep[state]);
  1258. UInt32 offs, curBack, posSlot;
  1259. UInt32 lenTest;
  1260. while (lenEnd < cur + newLen)
  1261. p->opt[++lenEnd].price = kInfinityPrice;
  1262. offs = 0;
  1263. while (startLen > matches[offs])
  1264. offs += 2;
  1265. curBack = matches[(size_t)offs + 1];
  1266. GetPosSlot2(curBack, posSlot);
  1267. for (lenTest = /*2*/ startLen; ; lenTest++)
  1268. {
  1269. UInt32 curAndLenPrice = normalMatchPrice + p->lenEnc.prices[posState][(size_t)lenTest - LZMA_MATCH_LEN_MIN];
  1270. {
  1271. UInt32 lenToPosState = GetLenToPosState(lenTest);
  1272. COptimal *opt;
  1273. if (curBack < kNumFullDistances)
  1274. curAndLenPrice += p->distancesPrices[lenToPosState][curBack];
  1275. else
  1276. curAndLenPrice += p->posSlotPrices[lenToPosState][posSlot] + p->alignPrices[curBack & kAlignMask];
  1277. opt = &p->opt[cur + lenTest];
  1278. if (curAndLenPrice < opt->price)
  1279. {
  1280. opt->price = curAndLenPrice;
  1281. opt->posPrev = cur;
  1282. opt->backPrev = curBack + LZMA_NUM_REPS;
  1283. opt->prev1IsChar = False;
  1284. }
  1285. }
  1286. if (/*_maxMode && */lenTest == matches[offs])
  1287. {
  1288. /* Try Match + Literal + Rep0 */
  1289. const Byte *data2 = data - curBack - 1;
  1290. UInt32 lenTest2 = lenTest + 1;
  1291. UInt32 limit = lenTest2 + p->numFastBytes;
  1292. if (limit > numAvailFull)
  1293. limit = numAvailFull;
  1294. for (; lenTest2 < limit && data[lenTest2] == data2[lenTest2]; lenTest2++);
  1295. lenTest2 -= lenTest + 1;
  1296. if (lenTest2 >= 2)
  1297. {
  1298. UInt32 nextRepMatchPrice;
  1299. UInt32 state2 = kMatchNextStates[state];
  1300. UInt32 posStateNext = (position + lenTest) & p->pbMask;
  1301. UInt32 curAndLenCharPrice = curAndLenPrice +
  1302. GET_PRICE_0(p->isMatch[state2][posStateNext]) +
  1303. LitEnc_GetPriceMatched(LIT_PROBS(position + lenTest, data[(size_t)lenTest - 1]),
  1304. data[lenTest], data2[lenTest], p->ProbPrices);
  1305. state2 = kLiteralNextStates[state2];
  1306. posStateNext = (posStateNext + 1) & p->pbMask;
  1307. nextRepMatchPrice = curAndLenCharPrice +
  1308. GET_PRICE_1(p->isMatch[state2][posStateNext]) +
  1309. GET_PRICE_1(p->isRep[state2]);
  1310. /* for (; lenTest2 >= 2; lenTest2--) */
  1311. {
  1312. UInt32 offset = cur + lenTest + 1 + lenTest2;
  1313. UInt32 curAndLenPrice2;
  1314. COptimal *opt;
  1315. while (lenEnd < offset)
  1316. p->opt[++lenEnd].price = kInfinityPrice;
  1317. curAndLenPrice2 = nextRepMatchPrice + GetRepPrice(p, 0, lenTest2, state2, posStateNext);
  1318. opt = &p->opt[offset];
  1319. if (curAndLenPrice2 < opt->price)
  1320. {
  1321. opt->price = curAndLenPrice2;
  1322. opt->posPrev = cur + lenTest + 1;
  1323. opt->backPrev = 0;
  1324. opt->prev1IsChar = True;
  1325. opt->prev2 = True;
  1326. opt->posPrev2 = cur;
  1327. opt->backPrev2 = curBack + LZMA_NUM_REPS;
  1328. }
  1329. }
  1330. }
  1331. offs += 2;
  1332. if (offs == numPairs)
  1333. break;
  1334. curBack = matches[(size_t)offs + 1];
  1335. if (curBack >= kNumFullDistances)
  1336. GetPosSlot2(curBack, posSlot);
  1337. }
  1338. }
  1339. }
  1340. }
  1341. }
  1342. #define ChangePair(smallDist, bigDist) (((bigDist) >> 7) > (smallDist))
  1343. static UInt32 GetOptimumFast(CLzmaEnc *p, UInt32 *backRes)
  1344. {
  1345. UInt32 numAvail, mainLen, mainDist, numPairs, repIndex, repLen, i;
  1346. const Byte *data;
  1347. const UInt32 *matches;
  1348. if (p->additionalOffset == 0)
  1349. mainLen = ReadMatchDistances(p, &numPairs);
  1350. else
  1351. {
  1352. mainLen = p->longestMatchLength;
  1353. numPairs = p->numPairs;
  1354. }
  1355. numAvail = p->numAvail;
  1356. *backRes = (UInt32)-1;
  1357. if (numAvail < 2)
  1358. return 1;
  1359. if (numAvail > LZMA_MATCH_LEN_MAX)
  1360. numAvail = LZMA_MATCH_LEN_MAX;
  1361. data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - 1;
  1362. repLen = repIndex = 0;
  1363. for (i = 0; i < LZMA_NUM_REPS; i++)
  1364. {
  1365. UInt32 len;
  1366. const Byte *data2 = data - p->reps[i] - 1;
  1367. if (data[0] != data2[0] || data[1] != data2[1])
  1368. continue;
  1369. for (len = 2; len < numAvail && data[len] == data2[len]; len++);
  1370. if (len >= p->numFastBytes)
  1371. {
  1372. *backRes = i;
  1373. MovePos(p, len - 1);
  1374. return len;
  1375. }
  1376. if (len > repLen)
  1377. {
  1378. repIndex = i;
  1379. repLen = len;
  1380. }
  1381. }
  1382. matches = p->matches;
  1383. if (mainLen >= p->numFastBytes)
  1384. {
  1385. *backRes = matches[(size_t)numPairs - 1] + LZMA_NUM_REPS;
  1386. MovePos(p, mainLen - 1);
  1387. return mainLen;
  1388. }
  1389. mainDist = 0; /* for GCC */
  1390. if (mainLen >= 2)
  1391. {
  1392. mainDist = matches[(size_t)numPairs - 1];
  1393. while (numPairs > 2 && mainLen == matches[(size_t)numPairs - 4] + 1)
  1394. {
  1395. if (!ChangePair(matches[(size_t)numPairs - 3], mainDist))
  1396. break;
  1397. numPairs -= 2;
  1398. mainLen = matches[(size_t)numPairs - 2];
  1399. mainDist = matches[(size_t)numPairs - 1];
  1400. }
  1401. if (mainLen == 2 && mainDist >= 0x80)
  1402. mainLen = 1;
  1403. }
  1404. if (repLen >= 2 && (
  1405. (repLen + 1 >= mainLen) ||
  1406. (repLen + 2 >= mainLen && mainDist >= (1 << 9)) ||
  1407. (repLen + 3 >= mainLen && mainDist >= (1 << 15))))
  1408. {
  1409. *backRes = repIndex;
  1410. MovePos(p, repLen - 1);
  1411. return repLen;
  1412. }
  1413. if (mainLen < 2 || numAvail <= 2)
  1414. return 1;
  1415. p->longestMatchLength = ReadMatchDistances(p, &p->numPairs);
  1416. if (p->longestMatchLength >= 2)
  1417. {
  1418. UInt32 newDistance = matches[(size_t)p->numPairs - 1];
  1419. if ((p->longestMatchLength >= mainLen && newDistance < mainDist) ||
  1420. (p->longestMatchLength == mainLen + 1 && !ChangePair(mainDist, newDistance)) ||
  1421. (p->longestMatchLength > mainLen + 1) ||
  1422. (p->longestMatchLength + 1 >= mainLen && mainLen >= 3 && ChangePair(newDistance, mainDist)))
  1423. return 1;
  1424. }
  1425. data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - 1;
  1426. for (i = 0; i < LZMA_NUM_REPS; i++)
  1427. {
  1428. UInt32 len, limit;
  1429. const Byte *data2 = data - p->reps[i] - 1;
  1430. if (data[0] != data2[0] || data[1] != data2[1])
  1431. continue;
  1432. limit = mainLen - 1;
  1433. for (len = 2; len < limit && data[len] == data2[len]; len++);
  1434. if (len >= limit)
  1435. return 1;
  1436. }
  1437. *backRes = mainDist + LZMA_NUM_REPS;
  1438. MovePos(p, mainLen - 2);
  1439. return mainLen;
  1440. }
  1441. static void WriteEndMarker(CLzmaEnc *p, UInt32 posState)
  1442. {
  1443. UInt32 len;
  1444. RangeEnc_EncodeBit(&p->rc, &p->isMatch[p->state][posState], 1);
  1445. RangeEnc_EncodeBit(&p->rc, &p->isRep[p->state], 0);
  1446. p->state = kMatchNextStates[p->state];
  1447. len = LZMA_MATCH_LEN_MIN;
  1448. LenEnc_Encode2(&p->lenEnc, &p->rc, len - LZMA_MATCH_LEN_MIN, posState, !p->fastMode, p->ProbPrices);
  1449. RcTree_Encode(&p->rc, p->posSlotEncoder[GetLenToPosState(len)], kNumPosSlotBits, (1 << kNumPosSlotBits) - 1);
  1450. RangeEnc_EncodeDirectBits(&p->rc, (((UInt32)1 << 30) - 1) >> kNumAlignBits, 30 - kNumAlignBits);
  1451. RcTree_ReverseEncode(&p->rc, p->posAlignEncoder, kNumAlignBits, kAlignMask);
  1452. }
  1453. static SRes CheckErrors(CLzmaEnc *p)
  1454. {
  1455. if (p->result != SZ_OK)
  1456. return p->result;
  1457. if (p->rc.res != SZ_OK)
  1458. p->result = SZ_ERROR_WRITE;
  1459. if (p->matchFinderBase.result != SZ_OK)
  1460. p->result = SZ_ERROR_READ;
  1461. if (p->result != SZ_OK)
  1462. p->finished = True;
  1463. return p->result;
  1464. }
  1465. static SRes Flush(CLzmaEnc *p, UInt32 nowPos)
  1466. {
  1467. /* ReleaseMFStream(); */
  1468. p->finished = True;
  1469. if (p->writeEndMark)
  1470. WriteEndMarker(p, nowPos & p->pbMask);
  1471. RangeEnc_FlushData(&p->rc);
  1472. RangeEnc_FlushStream(&p->rc);
  1473. return CheckErrors(p);
  1474. }
  1475. static void FillAlignPrices(CLzmaEnc *p)
  1476. {
  1477. UInt32 i;
  1478. for (i = 0; i < kAlignTableSize; i++)
  1479. p->alignPrices[i] = RcTree_ReverseGetPrice(p->posAlignEncoder, kNumAlignBits, i, p->ProbPrices);
  1480. p->alignPriceCount = 0;
  1481. }
  1482. static void FillDistancesPrices(CLzmaEnc *p)
  1483. {
  1484. UInt32 tempPrices[kNumFullDistances];
  1485. UInt32 i, lenToPosState;
  1486. for (i = kStartPosModelIndex; i < kNumFullDistances; i++)
  1487. {
  1488. UInt32 posSlot = GetPosSlot1(i);
  1489. UInt32 footerBits = ((posSlot >> 1) - 1);
  1490. UInt32 base = ((2 | (posSlot & 1)) << footerBits);
  1491. tempPrices[i] = RcTree_ReverseGetPrice(p->posEncoders + base - posSlot - 1, footerBits, i - base, p->ProbPrices);
  1492. }
  1493. for (lenToPosState = 0; lenToPosState < kNumLenToPosStates; lenToPosState++)
  1494. {
  1495. UInt32 posSlot;
  1496. const CLzmaProb *encoder = p->posSlotEncoder[lenToPosState];
  1497. UInt32 *posSlotPrices = p->posSlotPrices[lenToPosState];
  1498. for (posSlot = 0; posSlot < p->distTableSize; posSlot++)
  1499. posSlotPrices[posSlot] = RcTree_GetPrice(encoder, kNumPosSlotBits, posSlot, p->ProbPrices);
  1500. for (posSlot = kEndPosModelIndex; posSlot < p->distTableSize; posSlot++)
  1501. posSlotPrices[posSlot] += ((((posSlot >> 1) - 1) - kNumAlignBits) << kNumBitPriceShiftBits);
  1502. {
  1503. UInt32 *distancesPrices = p->distancesPrices[lenToPosState];
  1504. for (i = 0; i < kStartPosModelIndex; i++)
  1505. distancesPrices[i] = posSlotPrices[i];
  1506. for (; i < kNumFullDistances; i++)
  1507. distancesPrices[i] = posSlotPrices[GetPosSlot1(i)] + tempPrices[i];
  1508. }
  1509. }
  1510. p->matchPriceCount = 0;
  1511. }
  1512. void LzmaEnc_Construct(CLzmaEnc *p)
  1513. {
  1514. RangeEnc_Construct(&p->rc);
  1515. MatchFinder_Construct(&p->matchFinderBase);
  1516. #ifndef _7ZIP_ST
  1517. MatchFinderMt_Construct(&p->matchFinderMt);
  1518. p->matchFinderMt.MatchFinder = &p->matchFinderBase;
  1519. #endif
  1520. {
  1521. CLzmaEncProps props;
  1522. LzmaEncProps_Init(&props);
  1523. LzmaEnc_SetProps(p, &props);
  1524. }
  1525. #ifndef LZMA_LOG_BSR
  1526. LzmaEnc_FastPosInit(p->g_FastPos);
  1527. #endif
  1528. LzmaEnc_InitPriceTables(p->ProbPrices);
  1529. p->litProbs = NULL;
  1530. p->saveState.litProbs = NULL;
  1531. }
  1532. CLzmaEncHandle LzmaEnc_Create(ISzAllocPtr alloc)
  1533. {
  1534. void *p;
  1535. p = ISzAlloc_Alloc(alloc, sizeof(CLzmaEnc));
  1536. if (p)
  1537. LzmaEnc_Construct((CLzmaEnc *)p);
  1538. return p;
  1539. }
  1540. void LzmaEnc_FreeLits(CLzmaEnc *p, ISzAllocPtr alloc)
  1541. {
  1542. ISzAlloc_Free(alloc, p->litProbs);
  1543. ISzAlloc_Free(alloc, p->saveState.litProbs);
  1544. p->litProbs = NULL;
  1545. p->saveState.litProbs = NULL;
  1546. }
  1547. void LzmaEnc_Destruct(CLzmaEnc *p, ISzAllocPtr alloc, ISzAllocPtr allocBig)
  1548. {
  1549. #ifndef _7ZIP_ST
  1550. MatchFinderMt_Destruct(&p->matchFinderMt, allocBig);
  1551. #endif
  1552. MatchFinder_Free(&p->matchFinderBase, allocBig);
  1553. LzmaEnc_FreeLits(p, alloc);
  1554. RangeEnc_Free(&p->rc, alloc);
  1555. }
  1556. void LzmaEnc_Destroy(CLzmaEncHandle p, ISzAllocPtr alloc, ISzAllocPtr allocBig)
  1557. {
  1558. LzmaEnc_Destruct((CLzmaEnc *)p, alloc, allocBig);
  1559. ISzAlloc_Free(alloc, p);
  1560. }
  1561. static SRes LzmaEnc_CodeOneBlock(CLzmaEnc *p, Bool useLimits, UInt32 maxPackSize, UInt32 maxUnpackSize)
  1562. {
  1563. UInt32 nowPos32, startPos32;
  1564. if (p->needInit)
  1565. {
  1566. p->matchFinder.Init(p->matchFinderObj);
  1567. p->needInit = 0;
  1568. }
  1569. if (p->finished)
  1570. return p->result;
  1571. RINOK(CheckErrors(p));
  1572. nowPos32 = (UInt32)p->nowPos64;
  1573. startPos32 = nowPos32;
  1574. if (p->nowPos64 == 0)
  1575. {
  1576. UInt32 numPairs;
  1577. Byte curByte;
  1578. if (p->matchFinder.GetNumAvailableBytes(p->matchFinderObj) == 0)
  1579. return Flush(p, nowPos32);
  1580. ReadMatchDistances(p, &numPairs);
  1581. RangeEnc_EncodeBit(&p->rc, &p->isMatch[p->state][0], 0);
  1582. p->state = kLiteralNextStates[p->state];
  1583. curByte = *(p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - p->additionalOffset);
  1584. LitEnc_Encode(&p->rc, p->litProbs, curByte);
  1585. p->additionalOffset--;
  1586. nowPos32++;
  1587. }
  1588. if (p->matchFinder.GetNumAvailableBytes(p->matchFinderObj) != 0)
  1589. for (;;)
  1590. {
  1591. UInt32 pos, len, posState;
  1592. if (p->fastMode)
  1593. len = GetOptimumFast(p, &pos);
  1594. else
  1595. len = GetOptimum(p, nowPos32, &pos);
  1596. #ifdef SHOW_STAT2
  1597. printf("\n pos = %4X, len = %u pos = %u", nowPos32, len, pos);
  1598. #endif
  1599. posState = nowPos32 & p->pbMask;
  1600. if (len == 1 && pos == (UInt32)-1)
  1601. {
  1602. Byte curByte;
  1603. CLzmaProb *probs;
  1604. const Byte *data;
  1605. RangeEnc_EncodeBit(&p->rc, &p->isMatch[p->state][posState], 0);
  1606. data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - p->additionalOffset;
  1607. curByte = *data;
  1608. probs = LIT_PROBS(nowPos32, *(data - 1));
  1609. if (IsCharState(p->state))
  1610. LitEnc_Encode(&p->rc, probs, curByte);
  1611. else
  1612. LitEnc_EncodeMatched(&p->rc, probs, curByte, *(data - p->reps[0] - 1));
  1613. p->state = kLiteralNextStates[p->state];
  1614. }
  1615. else
  1616. {
  1617. RangeEnc_EncodeBit(&p->rc, &p->isMatch[p->state][posState], 1);
  1618. if (pos < LZMA_NUM_REPS)
  1619. {
  1620. RangeEnc_EncodeBit(&p->rc, &p->isRep[p->state], 1);
  1621. if (pos == 0)
  1622. {
  1623. RangeEnc_EncodeBit(&p->rc, &p->isRepG0[p->state], 0);
  1624. RangeEnc_EncodeBit(&p->rc, &p->isRep0Long[p->state][posState], ((len == 1) ? 0 : 1));
  1625. }
  1626. else
  1627. {
  1628. UInt32 distance = p->reps[pos];
  1629. RangeEnc_EncodeBit(&p->rc, &p->isRepG0[p->state], 1);
  1630. if (pos == 1)
  1631. RangeEnc_EncodeBit(&p->rc, &p->isRepG1[p->state], 0);
  1632. else
  1633. {
  1634. RangeEnc_EncodeBit(&p->rc, &p->isRepG1[p->state], 1);
  1635. RangeEnc_EncodeBit(&p->rc, &p->isRepG2[p->state], pos - 2);
  1636. if (pos == 3)
  1637. p->reps[3] = p->reps[2];
  1638. p->reps[2] = p->reps[1];
  1639. }
  1640. p->reps[1] = p->reps[0];
  1641. p->reps[0] = distance;
  1642. }
  1643. if (len == 1)
  1644. p->state = kShortRepNextStates[p->state];
  1645. else
  1646. {
  1647. LenEnc_Encode2(&p->repLenEnc, &p->rc, len - LZMA_MATCH_LEN_MIN, posState, !p->fastMode, p->ProbPrices);
  1648. p->state = kRepNextStates[p->state];
  1649. }
  1650. }
  1651. else
  1652. {
  1653. UInt32 posSlot;
  1654. RangeEnc_EncodeBit(&p->rc, &p->isRep[p->state], 0);
  1655. p->state = kMatchNextStates[p->state];
  1656. LenEnc_Encode2(&p->lenEnc, &p->rc, len - LZMA_MATCH_LEN_MIN, posState, !p->fastMode, p->ProbPrices);
  1657. pos -= LZMA_NUM_REPS;
  1658. GetPosSlot(pos, posSlot);
  1659. RcTree_Encode(&p->rc, p->posSlotEncoder[GetLenToPosState(len)], kNumPosSlotBits, posSlot);
  1660. if (posSlot >= kStartPosModelIndex)
  1661. {
  1662. UInt32 footerBits = ((posSlot >> 1) - 1);
  1663. UInt32 base = ((2 | (posSlot & 1)) << footerBits);
  1664. UInt32 posReduced = pos - base;
  1665. if (posSlot < kEndPosModelIndex)
  1666. RcTree_ReverseEncode(&p->rc, p->posEncoders + base - posSlot - 1, footerBits, posReduced);
  1667. else
  1668. {
  1669. RangeEnc_EncodeDirectBits(&p->rc, posReduced >> kNumAlignBits, footerBits - kNumAlignBits);
  1670. RcTree_ReverseEncode(&p->rc, p->posAlignEncoder, kNumAlignBits, posReduced & kAlignMask);
  1671. p->alignPriceCount++;
  1672. }
  1673. }
  1674. p->reps[3] = p->reps[2];
  1675. p->reps[2] = p->reps[1];
  1676. p->reps[1] = p->reps[0];
  1677. p->reps[0] = pos;
  1678. p->matchPriceCount++;
  1679. }
  1680. }
  1681. p->additionalOffset -= len;
  1682. nowPos32 += len;
  1683. if (p->additionalOffset == 0)
  1684. {
  1685. UInt32 processed;
  1686. if (!p->fastMode)
  1687. {
  1688. if (p->matchPriceCount >= (1 << 7))
  1689. FillDistancesPrices(p);
  1690. if (p->alignPriceCount >= kAlignTableSize)
  1691. FillAlignPrices(p);
  1692. }
  1693. if (p->matchFinder.GetNumAvailableBytes(p->matchFinderObj) == 0)
  1694. break;
  1695. processed = nowPos32 - startPos32;
  1696. if (useLimits)
  1697. {
  1698. if (processed + kNumOpts + 300 >= maxUnpackSize ||
  1699. RangeEnc_GetProcessed(&p->rc) + kNumOpts * 2 >= maxPackSize)
  1700. break;
  1701. }
  1702. else if (processed >= (1 << 17))
  1703. {
  1704. p->nowPos64 += nowPos32 - startPos32;
  1705. return CheckErrors(p);
  1706. }
  1707. }
  1708. }
  1709. p->nowPos64 += nowPos32 - startPos32;
  1710. return Flush(p, nowPos32);
  1711. }
  1712. #define kBigHashDicLimit ((UInt32)1 << 24)
  1713. static SRes LzmaEnc_Alloc(CLzmaEnc *p, UInt32 keepWindowSize, ISzAllocPtr alloc, ISzAllocPtr allocBig)
  1714. {
  1715. UInt32 beforeSize = kNumOpts;
  1716. if (!RangeEnc_Alloc(&p->rc, alloc))
  1717. return SZ_ERROR_MEM;
  1718. #ifndef _7ZIP_ST
  1719. p->mtMode = (p->multiThread && !p->fastMode && (p->matchFinderBase.btMode != 0));
  1720. #endif
  1721. {
  1722. unsigned lclp = p->lc + p->lp;
  1723. if (!p->litProbs || !p->saveState.litProbs || p->lclp != lclp)
  1724. {
  1725. LzmaEnc_FreeLits(p, alloc);
  1726. p->litProbs = (CLzmaProb *)ISzAlloc_Alloc(alloc, ((UInt32)0x300 << lclp) * sizeof(CLzmaProb));
  1727. p->saveState.litProbs = (CLzmaProb *)ISzAlloc_Alloc(alloc, ((UInt32)0x300 << lclp) * sizeof(CLzmaProb));
  1728. if (!p->litProbs || !p->saveState.litProbs)
  1729. {
  1730. LzmaEnc_FreeLits(p, alloc);
  1731. return SZ_ERROR_MEM;
  1732. }
  1733. p->lclp = lclp;
  1734. }
  1735. }
  1736. p->matchFinderBase.bigHash = (Byte)(p->dictSize > kBigHashDicLimit ? 1 : 0);
  1737. if (beforeSize + p->dictSize < keepWindowSize)
  1738. beforeSize = keepWindowSize - p->dictSize;
  1739. #ifndef _7ZIP_ST
  1740. if (p->mtMode)
  1741. {
  1742. RINOK(MatchFinderMt_Create(&p->matchFinderMt, p->dictSize, beforeSize, p->numFastBytes, LZMA_MATCH_LEN_MAX, allocBig));
  1743. p->matchFinderObj = &p->matchFinderMt;
  1744. MatchFinderMt_CreateVTable(&p->matchFinderMt, &p->matchFinder);
  1745. }
  1746. else
  1747. #endif
  1748. {
  1749. if (!MatchFinder_Create(&p->matchFinderBase, p->dictSize, beforeSize, p->numFastBytes, LZMA_MATCH_LEN_MAX, allocBig))
  1750. return SZ_ERROR_MEM;
  1751. p->matchFinderObj = &p->matchFinderBase;
  1752. MatchFinder_CreateVTable(&p->matchFinderBase, &p->matchFinder);
  1753. }
  1754. return SZ_OK;
  1755. }
  1756. void LzmaEnc_Init(CLzmaEnc *p)
  1757. {
  1758. UInt32 i;
  1759. p->state = 0;
  1760. for (i = 0 ; i < LZMA_NUM_REPS; i++)
  1761. p->reps[i] = 0;
  1762. RangeEnc_Init(&p->rc);
  1763. for (i = 0; i < kNumStates; i++)
  1764. {
  1765. UInt32 j;
  1766. for (j = 0; j < LZMA_NUM_PB_STATES_MAX; j++)
  1767. {
  1768. p->isMatch[i][j] = kProbInitValue;
  1769. p->isRep0Long[i][j] = kProbInitValue;
  1770. }
  1771. p->isRep[i] = kProbInitValue;
  1772. p->isRepG0[i] = kProbInitValue;
  1773. p->isRepG1[i] = kProbInitValue;
  1774. p->isRepG2[i] = kProbInitValue;
  1775. }
  1776. {
  1777. UInt32 num = (UInt32)0x300 << (p->lp + p->lc);
  1778. CLzmaProb *probs = p->litProbs;
  1779. for (i = 0; i < num; i++)
  1780. probs[i] = kProbInitValue;
  1781. }
  1782. {
  1783. for (i = 0; i < kNumLenToPosStates; i++)
  1784. {
  1785. CLzmaProb *probs = p->posSlotEncoder[i];
  1786. UInt32 j;
  1787. for (j = 0; j < (1 << kNumPosSlotBits); j++)
  1788. probs[j] = kProbInitValue;
  1789. }
  1790. }
  1791. {
  1792. for (i = 0; i < kNumFullDistances - kEndPosModelIndex; i++)
  1793. p->posEncoders[i] = kProbInitValue;
  1794. }
  1795. LenEnc_Init(&p->lenEnc.p);
  1796. LenEnc_Init(&p->repLenEnc.p);
  1797. for (i = 0; i < (1 << kNumAlignBits); i++)
  1798. p->posAlignEncoder[i] = kProbInitValue;
  1799. p->optimumEndIndex = 0;
  1800. p->optimumCurrentIndex = 0;
  1801. p->additionalOffset = 0;
  1802. p->pbMask = (1 << p->pb) - 1;
  1803. p->lpMask = (1 << p->lp) - 1;
  1804. }
  1805. void LzmaEnc_InitPrices(CLzmaEnc *p)
  1806. {
  1807. if (!p->fastMode)
  1808. {
  1809. FillDistancesPrices(p);
  1810. FillAlignPrices(p);
  1811. }
  1812. p->lenEnc.tableSize =
  1813. p->repLenEnc.tableSize =
  1814. p->numFastBytes + 1 - LZMA_MATCH_LEN_MIN;
  1815. LenPriceEnc_UpdateTables(&p->lenEnc, 1 << p->pb, p->ProbPrices);
  1816. LenPriceEnc_UpdateTables(&p->repLenEnc, 1 << p->pb, p->ProbPrices);
  1817. }
  1818. static SRes LzmaEnc_AllocAndInit(CLzmaEnc *p, UInt32 keepWindowSize, ISzAllocPtr alloc, ISzAllocPtr allocBig)
  1819. {
  1820. UInt32 i;
  1821. for (i = 0; i < (UInt32)kDicLogSizeMaxCompress; i++)
  1822. if (p->dictSize <= ((UInt32)1 << i))
  1823. break;
  1824. p->distTableSize = i * 2;
  1825. p->finished = False;
  1826. p->result = SZ_OK;
  1827. RINOK(LzmaEnc_Alloc(p, keepWindowSize, alloc, allocBig));
  1828. LzmaEnc_Init(p);
  1829. LzmaEnc_InitPrices(p);
  1830. p->nowPos64 = 0;
  1831. return SZ_OK;
  1832. }
  1833. static SRes LzmaEnc_Prepare(CLzmaEncHandle pp, ISeqOutStream *outStream, ISeqInStream *inStream,
  1834. ISzAllocPtr alloc, ISzAllocPtr allocBig)
  1835. {
  1836. CLzmaEnc *p = (CLzmaEnc *)pp;
  1837. p->matchFinderBase.stream = inStream;
  1838. p->needInit = 1;
  1839. p->rc.outStream = outStream;
  1840. return LzmaEnc_AllocAndInit(p, 0, alloc, allocBig);
  1841. }
  1842. SRes LzmaEnc_PrepareForLzma2(CLzmaEncHandle pp,
  1843. ISeqInStream *inStream, UInt32 keepWindowSize,
  1844. ISzAllocPtr alloc, ISzAllocPtr allocBig)
  1845. {
  1846. CLzmaEnc *p = (CLzmaEnc *)pp;
  1847. p->matchFinderBase.stream = inStream;
  1848. p->needInit = 1;
  1849. return LzmaEnc_AllocAndInit(p, keepWindowSize, alloc, allocBig);
  1850. }
  1851. static void LzmaEnc_SetInputBuf(CLzmaEnc *p, const Byte *src, SizeT srcLen)
  1852. {
  1853. p->matchFinderBase.directInput = 1;
  1854. p->matchFinderBase.bufferBase = (Byte *)src;
  1855. p->matchFinderBase.directInputRem = srcLen;
  1856. }
  1857. SRes LzmaEnc_MemPrepare(CLzmaEncHandle pp, const Byte *src, SizeT srcLen,
  1858. UInt32 keepWindowSize, ISzAllocPtr alloc, ISzAllocPtr allocBig)
  1859. {
  1860. CLzmaEnc *p = (CLzmaEnc *)pp;
  1861. LzmaEnc_SetInputBuf(p, src, srcLen);
  1862. p->needInit = 1;
  1863. return LzmaEnc_AllocAndInit(p, keepWindowSize, alloc, allocBig);
  1864. }
  1865. void LzmaEnc_Finish(CLzmaEncHandle pp)
  1866. {
  1867. #ifndef _7ZIP_ST
  1868. CLzmaEnc *p = (CLzmaEnc *)pp;
  1869. if (p->mtMode)
  1870. MatchFinderMt_ReleaseStream(&p->matchFinderMt);
  1871. #else
  1872. UNUSED_VAR(pp);
  1873. #endif
  1874. }
  1875. typedef struct
  1876. {
  1877. ISeqOutStream funcTable;
  1878. Byte *data;
  1879. SizeT rem;
  1880. Bool overflow;
  1881. } CSeqOutStreamBuf;
  1882. static size_t MyWrite(const ISeqOutStream *pp, const void *data, size_t size)
  1883. {
  1884. CSeqOutStreamBuf *p = CONTAINER_FROM_VTBL(pp, CSeqOutStreamBuf, funcTable);
  1885. if (p->rem < size)
  1886. {
  1887. size = p->rem;
  1888. p->overflow = True;
  1889. }
  1890. memcpy(p->data, data, size);
  1891. p->rem -= size;
  1892. p->data += size;
  1893. return size;
  1894. }
  1895. UInt32 LzmaEnc_GetNumAvailableBytes(CLzmaEncHandle pp)
  1896. {
  1897. const CLzmaEnc *p = (CLzmaEnc *)pp;
  1898. return p->matchFinder.GetNumAvailableBytes(p->matchFinderObj);
  1899. }
  1900. const Byte *LzmaEnc_GetCurBuf(CLzmaEncHandle pp)
  1901. {
  1902. const CLzmaEnc *p = (CLzmaEnc *)pp;
  1903. return p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - p->additionalOffset;
  1904. }
  1905. SRes LzmaEnc_CodeOneMemBlock(CLzmaEncHandle pp, Bool reInit,
  1906. Byte *dest, size_t *destLen, UInt32 desiredPackSize, UInt32 *unpackSize)
  1907. {
  1908. CLzmaEnc *p = (CLzmaEnc *)pp;
  1909. UInt64 nowPos64;
  1910. SRes res;
  1911. CSeqOutStreamBuf outStream;
  1912. outStream.funcTable.Write = MyWrite;
  1913. outStream.data = dest;
  1914. outStream.rem = *destLen;
  1915. outStream.overflow = False;
  1916. p->writeEndMark = False;
  1917. p->finished = False;
  1918. p->result = SZ_OK;
  1919. if (reInit)
  1920. LzmaEnc_Init(p);
  1921. LzmaEnc_InitPrices(p);
  1922. nowPos64 = p->nowPos64;
  1923. RangeEnc_Init(&p->rc);
  1924. p->rc.outStream = &outStream.funcTable;
  1925. res = LzmaEnc_CodeOneBlock(p, True, desiredPackSize, *unpackSize);
  1926. *unpackSize = (UInt32)(p->nowPos64 - nowPos64);
  1927. *destLen -= outStream.rem;
  1928. if (outStream.overflow)
  1929. return SZ_ERROR_OUTPUT_EOF;
  1930. return res;
  1931. }
  1932. static SRes LzmaEnc_Encode2(CLzmaEnc *p, ICompressProgress *progress)
  1933. {
  1934. SRes res = SZ_OK;
  1935. #ifndef _7ZIP_ST
  1936. Byte allocaDummy[0x300];
  1937. allocaDummy[0] = 0;
  1938. allocaDummy[1] = allocaDummy[0];
  1939. #endif
  1940. for (;;)
  1941. {
  1942. res = LzmaEnc_CodeOneBlock(p, False, 0, 0);
  1943. if (res != SZ_OK || p->finished)
  1944. break;
  1945. if (progress)
  1946. {
  1947. res = ICompressProgress_Progress(progress, p->nowPos64, RangeEnc_GetProcessed(&p->rc));
  1948. if (res != SZ_OK)
  1949. {
  1950. res = SZ_ERROR_PROGRESS;
  1951. break;
  1952. }
  1953. }
  1954. }
  1955. LzmaEnc_Finish(p);
  1956. /*
  1957. if (res == SZ_OK && !Inline_MatchFinder_IsFinishedOK(&p->matchFinderBase))
  1958. res = SZ_ERROR_FAIL;
  1959. }
  1960. */
  1961. return res;
  1962. }
  1963. SRes LzmaEnc_Encode(CLzmaEncHandle pp, ISeqOutStream *outStream, ISeqInStream *inStream, ICompressProgress *progress,
  1964. ISzAllocPtr alloc, ISzAllocPtr allocBig)
  1965. {
  1966. RINOK(LzmaEnc_Prepare(pp, outStream, inStream, alloc, allocBig));
  1967. return LzmaEnc_Encode2((CLzmaEnc *)pp, progress);
  1968. }
  1969. SRes LzmaEnc_WriteProperties(CLzmaEncHandle pp, Byte *props, SizeT *size)
  1970. {
  1971. CLzmaEnc *p = (CLzmaEnc *)pp;
  1972. unsigned i;
  1973. UInt32 dictSize = p->dictSize;
  1974. if (*size < LZMA_PROPS_SIZE)
  1975. return SZ_ERROR_PARAM;
  1976. *size = LZMA_PROPS_SIZE;
  1977. props[0] = (Byte)((p->pb * 5 + p->lp) * 9 + p->lc);
  1978. if (dictSize >= ((UInt32)1 << 22))
  1979. {
  1980. UInt32 kDictMask = ((UInt32)1 << 20) - 1;
  1981. if (dictSize < (UInt32)0xFFFFFFFF - kDictMask)
  1982. dictSize = (dictSize + kDictMask) & ~kDictMask;
  1983. }
  1984. else for (i = 11; i <= 30; i++)
  1985. {
  1986. if (dictSize <= ((UInt32)2 << i)) { dictSize = (2 << i); break; }
  1987. if (dictSize <= ((UInt32)3 << i)) { dictSize = (3 << i); break; }
  1988. }
  1989. for (i = 0; i < 4; i++)
  1990. props[1 + i] = (Byte)(dictSize >> (8 * i));
  1991. return SZ_OK;
  1992. }
  1993. unsigned LzmaEnc_IsWriteEndMark(CLzmaEncHandle pp)
  1994. {
  1995. return ((CLzmaEnc *)pp)->writeEndMark;
  1996. }
  1997. SRes LzmaEnc_MemEncode(CLzmaEncHandle pp, Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen,
  1998. int writeEndMark, ICompressProgress *progress, ISzAllocPtr alloc, ISzAllocPtr allocBig)
  1999. {
  2000. SRes res;
  2001. CLzmaEnc *p = (CLzmaEnc *)pp;
  2002. CSeqOutStreamBuf outStream;
  2003. outStream.funcTable.Write = MyWrite;
  2004. outStream.data = dest;
  2005. outStream.rem = *destLen;
  2006. outStream.overflow = False;
  2007. p->writeEndMark = writeEndMark;
  2008. p->rc.outStream = &outStream.funcTable;
  2009. res = LzmaEnc_MemPrepare(pp, src, srcLen, 0, alloc, allocBig);
  2010. if (res == SZ_OK)
  2011. {
  2012. res = LzmaEnc_Encode2(p, progress);
  2013. if (res == SZ_OK && p->nowPos64 != srcLen)
  2014. res = SZ_ERROR_FAIL;
  2015. }
  2016. *destLen -= outStream.rem;
  2017. if (outStream.overflow)
  2018. return SZ_ERROR_OUTPUT_EOF;
  2019. return res;
  2020. }
  2021. SRes LzmaEncode(Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen,
  2022. const CLzmaEncProps *props, Byte *propsEncoded, SizeT *propsSize, int writeEndMark,
  2023. ICompressProgress *progress, ISzAllocPtr alloc, ISzAllocPtr allocBig)
  2024. {
  2025. CLzmaEnc *p = (CLzmaEnc *)LzmaEnc_Create(alloc);
  2026. SRes res;
  2027. if (!p)
  2028. return SZ_ERROR_MEM;
  2029. res = LzmaEnc_SetProps(p, props);
  2030. if (res == SZ_OK)
  2031. {
  2032. res = LzmaEnc_WriteProperties(p, propsEncoded, propsSize);
  2033. if (res == SZ_OK)
  2034. res = LzmaEnc_MemEncode(p, dest, destLen, src, srcLen,
  2035. writeEndMark, progress, alloc, allocBig);
  2036. }
  2037. LzmaEnc_Destroy(p, alloc, allocBig);
  2038. return res;
  2039. }