LzmaEnc.c 77 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984
  1. /* LzmaEnc.c -- LZMA Encoder
  2. 2019-01-10: 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 kLzmaMaxHistorySize ((UInt32)3 << 29)
  19. /* #define kLzmaMaxHistorySize ((UInt32)7 << 29) */
  20. #define kNumTopBits 24
  21. #define kTopValue ((UInt32)1 << kNumTopBits)
  22. #define kNumBitModelTotalBits 11
  23. #define kBitModelTotal (1 << kNumBitModelTotalBits)
  24. #define kNumMoveBits 5
  25. #define kProbInitValue (kBitModelTotal >> 1)
  26. #define kNumMoveReducingBits 4
  27. #define kNumBitPriceShiftBits 4
  28. #define kBitPrice (1 << kNumBitPriceShiftBits)
  29. #define REP_LEN_COUNT 64
  30. void LzmaEncProps_Init(CLzmaEncProps *p)
  31. {
  32. p->level = 5;
  33. p->dictSize = p->mc = 0;
  34. p->reduceSize = (UInt64)(Int64)-1;
  35. p->lc = p->lp = p->pb = p->algo = p->fb = p->btMode = p->numHashBytes = p->numThreads = -1;
  36. p->writeEndMark = 0;
  37. }
  38. void LzmaEncProps_Normalize(CLzmaEncProps *p)
  39. {
  40. int level = p->level;
  41. if (level < 0) level = 5;
  42. p->level = level;
  43. if (p->dictSize == 0) p->dictSize = (level <= 5 ? (1 << (level * 2 + 14)) : (level <= 7 ? (1 << 25) : (1 << 26)));
  44. if (p->dictSize > p->reduceSize)
  45. {
  46. unsigned i;
  47. UInt32 reduceSize = (UInt32)p->reduceSize;
  48. for (i = 11; i <= 30; i++)
  49. {
  50. if (reduceSize <= ((UInt32)2 << i)) { p->dictSize = ((UInt32)2 << i); break; }
  51. if (reduceSize <= ((UInt32)3 << i)) { p->dictSize = ((UInt32)3 << i); break; }
  52. }
  53. }
  54. if (p->lc < 0) p->lc = 3;
  55. if (p->lp < 0) p->lp = 0;
  56. if (p->pb < 0) p->pb = 2;
  57. if (p->algo < 0) p->algo = (level < 5 ? 0 : 1);
  58. if (p->fb < 0) p->fb = (level < 7 ? 32 : 64);
  59. if (p->btMode < 0) p->btMode = (p->algo == 0 ? 0 : 1);
  60. if (p->numHashBytes < 0) p->numHashBytes = 4;
  61. if (p->mc == 0) p->mc = (16 + (p->fb >> 1)) >> (p->btMode ? 0 : 1);
  62. if (p->numThreads < 0)
  63. p->numThreads =
  64. #ifndef _7ZIP_ST
  65. ((p->btMode && p->algo) ? 2 : 1);
  66. #else
  67. 1;
  68. #endif
  69. }
  70. UInt32 LzmaEncProps_GetDictSize(const CLzmaEncProps *props2)
  71. {
  72. CLzmaEncProps props = *props2;
  73. LzmaEncProps_Normalize(&props);
  74. return props.dictSize;
  75. }
  76. #if (_MSC_VER >= 1400)
  77. /* BSR code is fast for some new CPUs */
  78. /* #define LZMA_LOG_BSR */
  79. #endif
  80. #ifdef LZMA_LOG_BSR
  81. #define kDicLogSizeMaxCompress 32
  82. #define BSR2_RET(pos, res) { unsigned long zz; _BitScanReverse(&zz, (pos)); res = (zz + zz) + ((pos >> (zz - 1)) & 1); }
  83. static unsigned GetPosSlot1(UInt32 pos)
  84. {
  85. unsigned res;
  86. BSR2_RET(pos, res);
  87. return res;
  88. }
  89. #define GetPosSlot2(pos, res) { BSR2_RET(pos, res); }
  90. #define GetPosSlot(pos, res) { if (pos < 2) res = pos; else BSR2_RET(pos, res); }
  91. #else
  92. #define kNumLogBits (9 + sizeof(size_t) / 2)
  93. /* #define kNumLogBits (11 + sizeof(size_t) / 8 * 3) */
  94. #define kDicLogSizeMaxCompress ((kNumLogBits - 1) * 2 + 7)
  95. static void LzmaEnc_FastPosInit(Byte *g_FastPos)
  96. {
  97. unsigned slot;
  98. g_FastPos[0] = 0;
  99. g_FastPos[1] = 1;
  100. g_FastPos += 2;
  101. for (slot = 2; slot < kNumLogBits * 2; slot++)
  102. {
  103. size_t k = ((size_t)1 << ((slot >> 1) - 1));
  104. size_t j;
  105. for (j = 0; j < k; j++)
  106. g_FastPos[j] = (Byte)slot;
  107. g_FastPos += k;
  108. }
  109. }
  110. /* we can use ((limit - pos) >> 31) only if (pos < ((UInt32)1 << 31)) */
  111. /*
  112. #define BSR2_RET(pos, res) { unsigned zz = 6 + ((kNumLogBits - 1) & \
  113. (0 - (((((UInt32)1 << (kNumLogBits + 6)) - 1) - pos) >> 31))); \
  114. res = p->g_FastPos[pos >> zz] + (zz * 2); }
  115. */
  116. /*
  117. #define BSR2_RET(pos, res) { unsigned zz = 6 + ((kNumLogBits - 1) & \
  118. (0 - (((((UInt32)1 << (kNumLogBits)) - 1) - (pos >> 6)) >> 31))); \
  119. res = p->g_FastPos[pos >> zz] + (zz * 2); }
  120. */
  121. #define BSR2_RET(pos, res) { unsigned zz = (pos < (1 << (kNumLogBits + 6))) ? 6 : 6 + kNumLogBits - 1; \
  122. res = p->g_FastPos[pos >> zz] + (zz * 2); }
  123. /*
  124. #define BSR2_RET(pos, res) { res = (pos < (1 << (kNumLogBits + 6))) ? \
  125. p->g_FastPos[pos >> 6] + 12 : \
  126. p->g_FastPos[pos >> (6 + kNumLogBits - 1)] + (6 + (kNumLogBits - 1)) * 2; }
  127. */
  128. #define GetPosSlot1(pos) p->g_FastPos[pos]
  129. #define GetPosSlot2(pos, res) { BSR2_RET(pos, res); }
  130. #define GetPosSlot(pos, res) { if (pos < kNumFullDistances) res = p->g_FastPos[pos & (kNumFullDistances - 1)]; else BSR2_RET(pos, res); }
  131. #endif
  132. #define LZMA_NUM_REPS 4
  133. typedef UInt16 CState;
  134. typedef UInt16 CExtra;
  135. typedef struct
  136. {
  137. UInt32 price;
  138. CState state;
  139. CExtra extra;
  140. // 0 : normal
  141. // 1 : LIT : MATCH
  142. // > 1 : MATCH (extra-1) : LIT : REP0 (len)
  143. UInt32 len;
  144. UInt32 dist;
  145. UInt32 reps[LZMA_NUM_REPS];
  146. } COptimal;
  147. // 18.06
  148. #define kNumOpts (1 << 11)
  149. #define kPackReserve (kNumOpts * 8)
  150. // #define kNumOpts (1 << 12)
  151. // #define kPackReserve (1 + kNumOpts * 2)
  152. #define kNumLenToPosStates 4
  153. #define kNumPosSlotBits 6
  154. #define kDicLogSizeMin 0
  155. #define kDicLogSizeMax 32
  156. #define kDistTableSizeMax (kDicLogSizeMax * 2)
  157. #define kNumAlignBits 4
  158. #define kAlignTableSize (1 << kNumAlignBits)
  159. #define kAlignMask (kAlignTableSize - 1)
  160. #define kStartPosModelIndex 4
  161. #define kEndPosModelIndex 14
  162. #define kNumFullDistances (1 << (kEndPosModelIndex >> 1))
  163. typedef
  164. #ifdef _LZMA_PROB32
  165. UInt32
  166. #else
  167. UInt16
  168. #endif
  169. CLzmaProb;
  170. #define LZMA_PB_MAX 4
  171. #define LZMA_LC_MAX 8
  172. #define LZMA_LP_MAX 4
  173. #define LZMA_NUM_PB_STATES_MAX (1 << LZMA_PB_MAX)
  174. #define kLenNumLowBits 3
  175. #define kLenNumLowSymbols (1 << kLenNumLowBits)
  176. #define kLenNumHighBits 8
  177. #define kLenNumHighSymbols (1 << kLenNumHighBits)
  178. #define kLenNumSymbolsTotal (kLenNumLowSymbols * 2 + 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 low[LZMA_NUM_PB_STATES_MAX << (kLenNumLowBits + 1)];
  185. CLzmaProb high[kLenNumHighSymbols];
  186. } CLenEnc;
  187. typedef struct
  188. {
  189. unsigned tableSize;
  190. UInt32 prices[LZMA_NUM_PB_STATES_MAX][kLenNumSymbolsTotal];
  191. // UInt32 prices1[LZMA_NUM_PB_STATES_MAX][kLenNumLowSymbols * 2];
  192. // UInt32 prices2[kLenNumSymbolsTotal];
  193. } CLenPriceEnc;
  194. #define GET_PRICE_LEN(p, posState, len) \
  195. ((p)->prices[posState][(size_t)(len) - LZMA_MATCH_LEN_MIN])
  196. /*
  197. #define GET_PRICE_LEN(p, posState, len) \
  198. ((p)->prices2[(size_t)(len) - 2] + ((p)->prices1[posState][((len) - 2) & (kLenNumLowSymbols * 2 - 1)] & (((len) - 2 - kLenNumLowSymbols * 2) >> 9)))
  199. */
  200. typedef struct
  201. {
  202. UInt32 range;
  203. unsigned cache;
  204. UInt64 low;
  205. UInt64 cacheSize;
  206. Byte *buf;
  207. Byte *bufLim;
  208. Byte *bufBase;
  209. ISeqOutStream *outStream;
  210. UInt64 processed;
  211. SRes res;
  212. } CRangeEnc;
  213. typedef struct
  214. {
  215. CLzmaProb *litProbs;
  216. unsigned state;
  217. UInt32 reps[LZMA_NUM_REPS];
  218. CLzmaProb posAlignEncoder[1 << kNumAlignBits];
  219. CLzmaProb isRep[kNumStates];
  220. CLzmaProb isRepG0[kNumStates];
  221. CLzmaProb isRepG1[kNumStates];
  222. CLzmaProb isRepG2[kNumStates];
  223. CLzmaProb isMatch[kNumStates][LZMA_NUM_PB_STATES_MAX];
  224. CLzmaProb isRep0Long[kNumStates][LZMA_NUM_PB_STATES_MAX];
  225. CLzmaProb posSlotEncoder[kNumLenToPosStates][1 << kNumPosSlotBits];
  226. CLzmaProb posEncoders[kNumFullDistances];
  227. CLenEnc lenProbs;
  228. CLenEnc repLenProbs;
  229. } CSaveState;
  230. typedef UInt32 CProbPrice;
  231. typedef struct
  232. {
  233. void *matchFinderObj;
  234. IMatchFinder matchFinder;
  235. unsigned optCur;
  236. unsigned optEnd;
  237. unsigned longestMatchLen;
  238. unsigned numPairs;
  239. UInt32 numAvail;
  240. unsigned state;
  241. unsigned numFastBytes;
  242. unsigned additionalOffset;
  243. UInt32 reps[LZMA_NUM_REPS];
  244. unsigned lpMask, pbMask;
  245. CLzmaProb *litProbs;
  246. CRangeEnc rc;
  247. UInt32 backRes;
  248. unsigned lc, lp, pb;
  249. unsigned lclp;
  250. BoolInt fastMode;
  251. BoolInt writeEndMark;
  252. BoolInt finished;
  253. BoolInt multiThread;
  254. BoolInt needInit;
  255. // BoolInt _maxMode;
  256. UInt64 nowPos64;
  257. unsigned matchPriceCount;
  258. // unsigned alignPriceCount;
  259. int repLenEncCounter;
  260. unsigned distTableSize;
  261. UInt32 dictSize;
  262. SRes result;
  263. #ifndef _7ZIP_ST
  264. BoolInt mtMode;
  265. // begin of CMatchFinderMt is used in LZ thread
  266. CMatchFinderMt matchFinderMt;
  267. // end of CMatchFinderMt is used in BT and HASH threads
  268. #endif
  269. CMatchFinder matchFinderBase;
  270. #ifndef _7ZIP_ST
  271. Byte pad[128];
  272. #endif
  273. // LZ thread
  274. CProbPrice ProbPrices[kBitModelTotal >> kNumMoveReducingBits];
  275. UInt32 matches[LZMA_MATCH_LEN_MAX * 2 + 2 + 1];
  276. UInt32 alignPrices[kAlignTableSize];
  277. UInt32 posSlotPrices[kNumLenToPosStates][kDistTableSizeMax];
  278. UInt32 distancesPrices[kNumLenToPosStates][kNumFullDistances];
  279. CLzmaProb posAlignEncoder[1 << kNumAlignBits];
  280. CLzmaProb isRep[kNumStates];
  281. CLzmaProb isRepG0[kNumStates];
  282. CLzmaProb isRepG1[kNumStates];
  283. CLzmaProb isRepG2[kNumStates];
  284. CLzmaProb isMatch[kNumStates][LZMA_NUM_PB_STATES_MAX];
  285. CLzmaProb isRep0Long[kNumStates][LZMA_NUM_PB_STATES_MAX];
  286. CLzmaProb posSlotEncoder[kNumLenToPosStates][1 << kNumPosSlotBits];
  287. CLzmaProb posEncoders[kNumFullDistances];
  288. CLenEnc lenProbs;
  289. CLenEnc repLenProbs;
  290. #ifndef LZMA_LOG_BSR
  291. Byte g_FastPos[1 << kNumLogBits];
  292. #endif
  293. CLenPriceEnc lenEnc;
  294. CLenPriceEnc repLenEnc;
  295. COptimal opt[kNumOpts];
  296. CSaveState saveState;
  297. #ifndef _7ZIP_ST
  298. Byte pad2[128];
  299. #endif
  300. } CLzmaEnc;
  301. #define COPY_ARR(dest, src, arr) memcpy(dest->arr, src->arr, sizeof(src->arr));
  302. void LzmaEnc_SaveState(CLzmaEncHandle pp)
  303. {
  304. CLzmaEnc *p = (CLzmaEnc *)pp;
  305. CSaveState *dest = &p->saveState;
  306. dest->state = p->state;
  307. dest->lenProbs = p->lenProbs;
  308. dest->repLenProbs = p->repLenProbs;
  309. COPY_ARR(dest, p, reps);
  310. COPY_ARR(dest, p, posAlignEncoder);
  311. COPY_ARR(dest, p, isRep);
  312. COPY_ARR(dest, p, isRepG0);
  313. COPY_ARR(dest, p, isRepG1);
  314. COPY_ARR(dest, p, isRepG2);
  315. COPY_ARR(dest, p, isMatch);
  316. COPY_ARR(dest, p, isRep0Long);
  317. COPY_ARR(dest, p, posSlotEncoder);
  318. COPY_ARR(dest, p, posEncoders);
  319. memcpy(dest->litProbs, p->litProbs, ((UInt32)0x300 << p->lclp) * sizeof(CLzmaProb));
  320. }
  321. void LzmaEnc_RestoreState(CLzmaEncHandle pp)
  322. {
  323. CLzmaEnc *dest = (CLzmaEnc *)pp;
  324. const CSaveState *p = &dest->saveState;
  325. dest->state = p->state;
  326. dest->lenProbs = p->lenProbs;
  327. dest->repLenProbs = p->repLenProbs;
  328. COPY_ARR(dest, p, reps);
  329. COPY_ARR(dest, p, posAlignEncoder);
  330. COPY_ARR(dest, p, isRep);
  331. COPY_ARR(dest, p, isRepG0);
  332. COPY_ARR(dest, p, isRepG1);
  333. COPY_ARR(dest, p, isRepG2);
  334. COPY_ARR(dest, p, isMatch);
  335. COPY_ARR(dest, p, isRep0Long);
  336. COPY_ARR(dest, p, posSlotEncoder);
  337. COPY_ARR(dest, p, posEncoders);
  338. memcpy(dest->litProbs, p->litProbs, ((UInt32)0x300 << dest->lclp) * sizeof(CLzmaProb));
  339. }
  340. SRes LzmaEnc_SetProps(CLzmaEncHandle pp, const CLzmaEncProps *props2)
  341. {
  342. CLzmaEnc *p = (CLzmaEnc *)pp;
  343. CLzmaEncProps props = *props2;
  344. LzmaEncProps_Normalize(&props);
  345. if (props.lc > LZMA_LC_MAX
  346. || props.lp > LZMA_LP_MAX
  347. || props.pb > LZMA_PB_MAX
  348. || props.dictSize > ((UInt64)1 << kDicLogSizeMaxCompress)
  349. || props.dictSize > kLzmaMaxHistorySize)
  350. return SZ_ERROR_PARAM;
  351. p->dictSize = props.dictSize;
  352. {
  353. unsigned fb = props.fb;
  354. if (fb < 5)
  355. fb = 5;
  356. if (fb > LZMA_MATCH_LEN_MAX)
  357. fb = LZMA_MATCH_LEN_MAX;
  358. p->numFastBytes = fb;
  359. }
  360. p->lc = props.lc;
  361. p->lp = props.lp;
  362. p->pb = props.pb;
  363. p->fastMode = (props.algo == 0);
  364. // p->_maxMode = True;
  365. p->matchFinderBase.btMode = (Byte)(props.btMode ? 1 : 0);
  366. {
  367. unsigned numHashBytes = 4;
  368. if (props.btMode)
  369. {
  370. if (props.numHashBytes < 2)
  371. numHashBytes = 2;
  372. else if (props.numHashBytes < 4)
  373. numHashBytes = props.numHashBytes;
  374. }
  375. p->matchFinderBase.numHashBytes = numHashBytes;
  376. }
  377. p->matchFinderBase.cutValue = props.mc;
  378. p->writeEndMark = props.writeEndMark;
  379. #ifndef _7ZIP_ST
  380. /*
  381. if (newMultiThread != _multiThread)
  382. {
  383. ReleaseMatchFinder();
  384. _multiThread = newMultiThread;
  385. }
  386. */
  387. p->multiThread = (props.numThreads > 1);
  388. #endif
  389. return SZ_OK;
  390. }
  391. void LzmaEnc_SetDataSize(CLzmaEncHandle pp, UInt64 expectedDataSiize)
  392. {
  393. CLzmaEnc *p = (CLzmaEnc *)pp;
  394. p->matchFinderBase.expectedDataSize = expectedDataSiize;
  395. }
  396. #define kState_Start 0
  397. #define kState_LitAfterMatch 4
  398. #define kState_LitAfterRep 5
  399. #define kState_MatchAfterLit 7
  400. #define kState_RepAfterLit 8
  401. static const Byte kLiteralNextStates[kNumStates] = {0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 4, 5};
  402. static const Byte kMatchNextStates[kNumStates] = {7, 7, 7, 7, 7, 7, 7, 10, 10, 10, 10, 10};
  403. static const Byte kRepNextStates[kNumStates] = {8, 8, 8, 8, 8, 8, 8, 11, 11, 11, 11, 11};
  404. static const Byte kShortRepNextStates[kNumStates]= {9, 9, 9, 9, 9, 9, 9, 11, 11, 11, 11, 11};
  405. #define IsLitState(s) ((s) < 7)
  406. #define GetLenToPosState2(len) (((len) < kNumLenToPosStates - 1) ? (len) : kNumLenToPosStates - 1)
  407. #define GetLenToPosState(len) (((len) < kNumLenToPosStates + 1) ? (len) - 2 : kNumLenToPosStates - 1)
  408. #define kInfinityPrice (1 << 30)
  409. static void RangeEnc_Construct(CRangeEnc *p)
  410. {
  411. p->outStream = NULL;
  412. p->bufBase = NULL;
  413. }
  414. #define RangeEnc_GetProcessed(p) ((p)->processed + ((p)->buf - (p)->bufBase) + (p)->cacheSize)
  415. #define RangeEnc_GetProcessed_sizet(p) ((size_t)(p)->processed + ((p)->buf - (p)->bufBase) + (size_t)(p)->cacheSize)
  416. #define RC_BUF_SIZE (1 << 16)
  417. static int RangeEnc_Alloc(CRangeEnc *p, ISzAllocPtr alloc)
  418. {
  419. if (!p->bufBase)
  420. {
  421. p->bufBase = (Byte *)ISzAlloc_Alloc(alloc, RC_BUF_SIZE);
  422. if (!p->bufBase)
  423. return 0;
  424. p->bufLim = p->bufBase + RC_BUF_SIZE;
  425. }
  426. return 1;
  427. }
  428. static void RangeEnc_Free(CRangeEnc *p, ISzAllocPtr alloc)
  429. {
  430. ISzAlloc_Free(alloc, p->bufBase);
  431. p->bufBase = 0;
  432. }
  433. static void RangeEnc_Init(CRangeEnc *p)
  434. {
  435. /* Stream.Init(); */
  436. p->range = 0xFFFFFFFF;
  437. p->cache = 0;
  438. p->low = 0;
  439. p->cacheSize = 0;
  440. p->buf = p->bufBase;
  441. p->processed = 0;
  442. p->res = SZ_OK;
  443. }
  444. MY_NO_INLINE static void RangeEnc_FlushStream(CRangeEnc *p)
  445. {
  446. size_t num;
  447. if (p->res != SZ_OK)
  448. return;
  449. num = p->buf - p->bufBase;
  450. if (num != ISeqOutStream_Write(p->outStream, p->bufBase, num))
  451. p->res = SZ_ERROR_WRITE;
  452. p->processed += num;
  453. p->buf = p->bufBase;
  454. }
  455. MY_NO_INLINE static void MY_FAST_CALL RangeEnc_ShiftLow(CRangeEnc *p)
  456. {
  457. UInt32 low = (UInt32)p->low;
  458. unsigned high = (unsigned)(p->low >> 32);
  459. p->low = (UInt32)(low << 8);
  460. if (low < (UInt32)0xFF000000 || high != 0)
  461. {
  462. {
  463. Byte *buf = p->buf;
  464. *buf++ = (Byte)(p->cache + high);
  465. p->cache = (unsigned)(low >> 24);
  466. p->buf = buf;
  467. if (buf == p->bufLim)
  468. RangeEnc_FlushStream(p);
  469. if (p->cacheSize == 0)
  470. return;
  471. }
  472. high += 0xFF;
  473. for (;;)
  474. {
  475. Byte *buf = p->buf;
  476. *buf++ = (Byte)(high);
  477. p->buf = buf;
  478. if (buf == p->bufLim)
  479. RangeEnc_FlushStream(p);
  480. if (--p->cacheSize == 0)
  481. return;
  482. }
  483. }
  484. p->cacheSize++;
  485. }
  486. static void RangeEnc_FlushData(CRangeEnc *p)
  487. {
  488. int i;
  489. for (i = 0; i < 5; i++)
  490. RangeEnc_ShiftLow(p);
  491. }
  492. #define RC_NORM(p) if (range < kTopValue) { range <<= 8; RangeEnc_ShiftLow(p); }
  493. #define RC_BIT_PRE(p, prob) \
  494. ttt = *(prob); \
  495. newBound = (range >> kNumBitModelTotalBits) * ttt;
  496. // #define _LZMA_ENC_USE_BRANCH
  497. #ifdef _LZMA_ENC_USE_BRANCH
  498. #define RC_BIT(p, prob, bit) { \
  499. RC_BIT_PRE(p, prob) \
  500. if (bit == 0) { range = newBound; ttt += (kBitModelTotal - ttt) >> kNumMoveBits; } \
  501. else { (p)->low += newBound; range -= newBound; ttt -= ttt >> kNumMoveBits; } \
  502. *(prob) = (CLzmaProb)ttt; \
  503. RC_NORM(p) \
  504. }
  505. #else
  506. #define RC_BIT(p, prob, bit) { \
  507. UInt32 mask; \
  508. RC_BIT_PRE(p, prob) \
  509. mask = 0 - (UInt32)bit; \
  510. range &= mask; \
  511. mask &= newBound; \
  512. range -= mask; \
  513. (p)->low += mask; \
  514. mask = (UInt32)bit - 1; \
  515. range += newBound & mask; \
  516. mask &= (kBitModelTotal - ((1 << kNumMoveBits) - 1)); \
  517. mask += ((1 << kNumMoveBits) - 1); \
  518. ttt += (Int32)(mask - ttt) >> kNumMoveBits; \
  519. *(prob) = (CLzmaProb)ttt; \
  520. RC_NORM(p) \
  521. }
  522. #endif
  523. #define RC_BIT_0_BASE(p, prob) \
  524. range = newBound; *(prob) = (CLzmaProb)(ttt + ((kBitModelTotal - ttt) >> kNumMoveBits));
  525. #define RC_BIT_1_BASE(p, prob) \
  526. range -= newBound; (p)->low += newBound; *(prob) = (CLzmaProb)(ttt - (ttt >> kNumMoveBits)); \
  527. #define RC_BIT_0(p, prob) \
  528. RC_BIT_0_BASE(p, prob) \
  529. RC_NORM(p)
  530. #define RC_BIT_1(p, prob) \
  531. RC_BIT_1_BASE(p, prob) \
  532. RC_NORM(p)
  533. static void RangeEnc_EncodeBit_0(CRangeEnc *p, CLzmaProb *prob)
  534. {
  535. UInt32 range, ttt, newBound;
  536. range = p->range;
  537. RC_BIT_PRE(p, prob)
  538. RC_BIT_0(p, prob)
  539. p->range = range;
  540. }
  541. static void LitEnc_Encode(CRangeEnc *p, CLzmaProb *probs, UInt32 sym)
  542. {
  543. UInt32 range = p->range;
  544. sym |= 0x100;
  545. do
  546. {
  547. UInt32 ttt, newBound;
  548. // RangeEnc_EncodeBit(p, probs + (sym >> 8), (sym >> 7) & 1);
  549. CLzmaProb *prob = probs + (sym >> 8);
  550. UInt32 bit = (sym >> 7) & 1;
  551. sym <<= 1;
  552. RC_BIT(p, prob, bit);
  553. }
  554. while (sym < 0x10000);
  555. p->range = range;
  556. }
  557. static void LitEnc_EncodeMatched(CRangeEnc *p, CLzmaProb *probs, UInt32 sym, UInt32 matchByte)
  558. {
  559. UInt32 range = p->range;
  560. UInt32 offs = 0x100;
  561. sym |= 0x100;
  562. do
  563. {
  564. UInt32 ttt, newBound;
  565. CLzmaProb *prob;
  566. UInt32 bit;
  567. matchByte <<= 1;
  568. // RangeEnc_EncodeBit(p, probs + (offs + (matchByte & offs) + (sym >> 8)), (sym >> 7) & 1);
  569. prob = probs + (offs + (matchByte & offs) + (sym >> 8));
  570. bit = (sym >> 7) & 1;
  571. sym <<= 1;
  572. offs &= ~(matchByte ^ sym);
  573. RC_BIT(p, prob, bit);
  574. }
  575. while (sym < 0x10000);
  576. p->range = range;
  577. }
  578. static void LzmaEnc_InitPriceTables(CProbPrice *ProbPrices)
  579. {
  580. UInt32 i;
  581. for (i = 0; i < (kBitModelTotal >> kNumMoveReducingBits); i++)
  582. {
  583. const unsigned kCyclesBits = kNumBitPriceShiftBits;
  584. UInt32 w = (i << kNumMoveReducingBits) + (1 << (kNumMoveReducingBits - 1));
  585. unsigned bitCount = 0;
  586. unsigned j;
  587. for (j = 0; j < kCyclesBits; j++)
  588. {
  589. w = w * w;
  590. bitCount <<= 1;
  591. while (w >= ((UInt32)1 << 16))
  592. {
  593. w >>= 1;
  594. bitCount++;
  595. }
  596. }
  597. ProbPrices[i] = (CProbPrice)((kNumBitModelTotalBits << kCyclesBits) - 15 - bitCount);
  598. // printf("\n%3d: %5d", i, ProbPrices[i]);
  599. }
  600. }
  601. #define GET_PRICE(prob, bit) \
  602. p->ProbPrices[((prob) ^ (unsigned)(((-(int)(bit))) & (kBitModelTotal - 1))) >> kNumMoveReducingBits];
  603. #define GET_PRICEa(prob, bit) \
  604. ProbPrices[((prob) ^ (unsigned)((-((int)(bit))) & (kBitModelTotal - 1))) >> kNumMoveReducingBits];
  605. #define GET_PRICE_0(prob) p->ProbPrices[(prob) >> kNumMoveReducingBits]
  606. #define GET_PRICE_1(prob) p->ProbPrices[((prob) ^ (kBitModelTotal - 1)) >> kNumMoveReducingBits]
  607. #define GET_PRICEa_0(prob) ProbPrices[(prob) >> kNumMoveReducingBits]
  608. #define GET_PRICEa_1(prob) ProbPrices[((prob) ^ (kBitModelTotal - 1)) >> kNumMoveReducingBits]
  609. static UInt32 LitEnc_GetPrice(const CLzmaProb *probs, UInt32 sym, const CProbPrice *ProbPrices)
  610. {
  611. UInt32 price = 0;
  612. sym |= 0x100;
  613. do
  614. {
  615. unsigned bit = sym & 1;
  616. sym >>= 1;
  617. price += GET_PRICEa(probs[sym], bit);
  618. }
  619. while (sym >= 2);
  620. return price;
  621. }
  622. static UInt32 LitEnc_Matched_GetPrice(const CLzmaProb *probs, UInt32 sym, UInt32 matchByte, const CProbPrice *ProbPrices)
  623. {
  624. UInt32 price = 0;
  625. UInt32 offs = 0x100;
  626. sym |= 0x100;
  627. do
  628. {
  629. matchByte <<= 1;
  630. price += GET_PRICEa(probs[offs + (matchByte & offs) + (sym >> 8)], (sym >> 7) & 1);
  631. sym <<= 1;
  632. offs &= ~(matchByte ^ sym);
  633. }
  634. while (sym < 0x10000);
  635. return price;
  636. }
  637. static void RcTree_ReverseEncode(CRangeEnc *rc, CLzmaProb *probs, unsigned numBits, unsigned sym)
  638. {
  639. UInt32 range = rc->range;
  640. unsigned m = 1;
  641. do
  642. {
  643. UInt32 ttt, newBound;
  644. unsigned bit = sym & 1;
  645. // RangeEnc_EncodeBit(rc, probs + m, bit);
  646. sym >>= 1;
  647. RC_BIT(rc, probs + m, bit);
  648. m = (m << 1) | bit;
  649. }
  650. while (--numBits);
  651. rc->range = range;
  652. }
  653. static void LenEnc_Init(CLenEnc *p)
  654. {
  655. unsigned i;
  656. for (i = 0; i < (LZMA_NUM_PB_STATES_MAX << (kLenNumLowBits + 1)); i++)
  657. p->low[i] = kProbInitValue;
  658. for (i = 0; i < kLenNumHighSymbols; i++)
  659. p->high[i] = kProbInitValue;
  660. }
  661. static void LenEnc_Encode(CLenEnc *p, CRangeEnc *rc, unsigned sym, unsigned posState)
  662. {
  663. UInt32 range, ttt, newBound;
  664. CLzmaProb *probs = p->low;
  665. range = rc->range;
  666. RC_BIT_PRE(rc, probs);
  667. if (sym >= kLenNumLowSymbols)
  668. {
  669. RC_BIT_1(rc, probs);
  670. probs += kLenNumLowSymbols;
  671. RC_BIT_PRE(rc, probs);
  672. if (sym >= kLenNumLowSymbols * 2)
  673. {
  674. RC_BIT_1(rc, probs);
  675. rc->range = range;
  676. // RcTree_Encode(rc, p->high, kLenNumHighBits, sym - kLenNumLowSymbols * 2);
  677. LitEnc_Encode(rc, p->high, sym - kLenNumLowSymbols * 2);
  678. return;
  679. }
  680. sym -= kLenNumLowSymbols;
  681. }
  682. // RcTree_Encode(rc, probs + (posState << kLenNumLowBits), kLenNumLowBits, sym);
  683. {
  684. unsigned m;
  685. unsigned bit;
  686. RC_BIT_0(rc, probs);
  687. probs += (posState << (1 + kLenNumLowBits));
  688. bit = (sym >> 2) ; RC_BIT(rc, probs + 1, bit); m = (1 << 1) + bit;
  689. bit = (sym >> 1) & 1; RC_BIT(rc, probs + m, bit); m = (m << 1) + bit;
  690. bit = sym & 1; RC_BIT(rc, probs + m, bit);
  691. rc->range = range;
  692. }
  693. }
  694. static void SetPrices_3(const CLzmaProb *probs, UInt32 startPrice, UInt32 *prices, const CProbPrice *ProbPrices)
  695. {
  696. unsigned i;
  697. for (i = 0; i < 8; i += 2)
  698. {
  699. UInt32 price = startPrice;
  700. UInt32 prob;
  701. price += GET_PRICEa(probs[1 ], (i >> 2));
  702. price += GET_PRICEa(probs[2 + (i >> 2)], (i >> 1) & 1);
  703. prob = probs[4 + (i >> 1)];
  704. prices[i ] = price + GET_PRICEa_0(prob);
  705. prices[i + 1] = price + GET_PRICEa_1(prob);
  706. }
  707. }
  708. MY_NO_INLINE static void MY_FAST_CALL LenPriceEnc_UpdateTables(
  709. CLenPriceEnc *p,
  710. unsigned numPosStates,
  711. const CLenEnc *enc,
  712. const CProbPrice *ProbPrices)
  713. {
  714. UInt32 b;
  715. {
  716. unsigned prob = enc->low[0];
  717. UInt32 a, c;
  718. unsigned posState;
  719. b = GET_PRICEa_1(prob);
  720. a = GET_PRICEa_0(prob);
  721. c = b + GET_PRICEa_0(enc->low[kLenNumLowSymbols]);
  722. for (posState = 0; posState < numPosStates; posState++)
  723. {
  724. UInt32 *prices = p->prices[posState];
  725. const CLzmaProb *probs = enc->low + (posState << (1 + kLenNumLowBits));
  726. SetPrices_3(probs, a, prices, ProbPrices);
  727. SetPrices_3(probs + kLenNumLowSymbols, c, prices + kLenNumLowSymbols, ProbPrices);
  728. }
  729. }
  730. /*
  731. {
  732. unsigned i;
  733. UInt32 b;
  734. a = GET_PRICEa_0(enc->low[0]);
  735. for (i = 0; i < kLenNumLowSymbols; i++)
  736. p->prices2[i] = a;
  737. a = GET_PRICEa_1(enc->low[0]);
  738. b = a + GET_PRICEa_0(enc->low[kLenNumLowSymbols]);
  739. for (i = kLenNumLowSymbols; i < kLenNumLowSymbols * 2; i++)
  740. p->prices2[i] = b;
  741. a += GET_PRICEa_1(enc->low[kLenNumLowSymbols]);
  742. }
  743. */
  744. // p->counter = numSymbols;
  745. // p->counter = 64;
  746. {
  747. unsigned i = p->tableSize;
  748. if (i > kLenNumLowSymbols * 2)
  749. {
  750. const CLzmaProb *probs = enc->high;
  751. UInt32 *prices = p->prices[0] + kLenNumLowSymbols * 2;
  752. i -= kLenNumLowSymbols * 2 - 1;
  753. i >>= 1;
  754. b += GET_PRICEa_1(enc->low[kLenNumLowSymbols]);
  755. do
  756. {
  757. /*
  758. p->prices2[i] = a +
  759. // RcTree_GetPrice(enc->high, kLenNumHighBits, i - kLenNumLowSymbols * 2, ProbPrices);
  760. LitEnc_GetPrice(probs, i - kLenNumLowSymbols * 2, ProbPrices);
  761. */
  762. // UInt32 price = a + RcTree_GetPrice(probs, kLenNumHighBits - 1, sym, ProbPrices);
  763. unsigned sym = --i + (1 << (kLenNumHighBits - 1));
  764. UInt32 price = b;
  765. do
  766. {
  767. unsigned bit = sym & 1;
  768. sym >>= 1;
  769. price += GET_PRICEa(probs[sym], bit);
  770. }
  771. while (sym >= 2);
  772. {
  773. unsigned prob = probs[(size_t)i + (1 << (kLenNumHighBits - 1))];
  774. prices[(size_t)i * 2 ] = price + GET_PRICEa_0(prob);
  775. prices[(size_t)i * 2 + 1] = price + GET_PRICEa_1(prob);
  776. }
  777. }
  778. while (i);
  779. {
  780. unsigned posState;
  781. size_t num = (p->tableSize - kLenNumLowSymbols * 2) * sizeof(p->prices[0][0]);
  782. for (posState = 1; posState < numPosStates; posState++)
  783. memcpy(p->prices[posState] + kLenNumLowSymbols * 2, p->prices[0] + kLenNumLowSymbols * 2, num);
  784. }
  785. }
  786. }
  787. }
  788. /*
  789. #ifdef SHOW_STAT
  790. g_STAT_OFFSET += num;
  791. printf("\n MovePos %u", num);
  792. #endif
  793. */
  794. #define MOVE_POS(p, num) { \
  795. p->additionalOffset += (num); \
  796. p->matchFinder.Skip(p->matchFinderObj, (UInt32)(num)); }
  797. static unsigned ReadMatchDistances(CLzmaEnc *p, unsigned *numPairsRes)
  798. {
  799. unsigned numPairs;
  800. p->additionalOffset++;
  801. p->numAvail = p->matchFinder.GetNumAvailableBytes(p->matchFinderObj);
  802. numPairs = p->matchFinder.GetMatches(p->matchFinderObj, p->matches);
  803. *numPairsRes = numPairs;
  804. #ifdef SHOW_STAT
  805. printf("\n i = %u numPairs = %u ", g_STAT_OFFSET, numPairs / 2);
  806. g_STAT_OFFSET++;
  807. {
  808. unsigned i;
  809. for (i = 0; i < numPairs; i += 2)
  810. printf("%2u %6u | ", p->matches[i], p->matches[i + 1]);
  811. }
  812. #endif
  813. if (numPairs == 0)
  814. return 0;
  815. {
  816. unsigned len = p->matches[(size_t)numPairs - 2];
  817. if (len != p->numFastBytes)
  818. return len;
  819. {
  820. UInt32 numAvail = p->numAvail;
  821. if (numAvail > LZMA_MATCH_LEN_MAX)
  822. numAvail = LZMA_MATCH_LEN_MAX;
  823. {
  824. const Byte *p1 = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - 1;
  825. const Byte *p2 = p1 + len;
  826. ptrdiff_t dif = (ptrdiff_t)-1 - p->matches[(size_t)numPairs - 1];
  827. const Byte *lim = p1 + numAvail;
  828. for (; p2 != lim && *p2 == p2[dif]; p2++)
  829. {}
  830. return (unsigned)(p2 - p1);
  831. }
  832. }
  833. }
  834. }
  835. #define MARK_LIT ((UInt32)(Int32)-1)
  836. #define MakeAs_Lit(p) { (p)->dist = MARK_LIT; (p)->extra = 0; }
  837. #define MakeAs_ShortRep(p) { (p)->dist = 0; (p)->extra = 0; }
  838. #define IsShortRep(p) ((p)->dist == 0)
  839. #define GetPrice_ShortRep(p, state, posState) \
  840. ( GET_PRICE_0(p->isRepG0[state]) + GET_PRICE_0(p->isRep0Long[state][posState]))
  841. #define GetPrice_Rep_0(p, state, posState) ( \
  842. GET_PRICE_1(p->isMatch[state][posState]) \
  843. + GET_PRICE_1(p->isRep0Long[state][posState])) \
  844. + GET_PRICE_1(p->isRep[state]) \
  845. + GET_PRICE_0(p->isRepG0[state])
  846. MY_FORCE_INLINE
  847. static UInt32 GetPrice_PureRep(const CLzmaEnc *p, unsigned repIndex, size_t state, size_t posState)
  848. {
  849. UInt32 price;
  850. UInt32 prob = p->isRepG0[state];
  851. if (repIndex == 0)
  852. {
  853. price = GET_PRICE_0(prob);
  854. price += GET_PRICE_1(p->isRep0Long[state][posState]);
  855. }
  856. else
  857. {
  858. price = GET_PRICE_1(prob);
  859. prob = p->isRepG1[state];
  860. if (repIndex == 1)
  861. price += GET_PRICE_0(prob);
  862. else
  863. {
  864. price += GET_PRICE_1(prob);
  865. price += GET_PRICE(p->isRepG2[state], repIndex - 2);
  866. }
  867. }
  868. return price;
  869. }
  870. static unsigned Backward(CLzmaEnc *p, unsigned cur)
  871. {
  872. unsigned wr = cur + 1;
  873. p->optEnd = wr;
  874. for (;;)
  875. {
  876. UInt32 dist = p->opt[cur].dist;
  877. unsigned len = (unsigned)p->opt[cur].len;
  878. unsigned extra = (unsigned)p->opt[cur].extra;
  879. cur -= len;
  880. if (extra)
  881. {
  882. wr--;
  883. p->opt[wr].len = (UInt32)len;
  884. cur -= extra;
  885. len = extra;
  886. if (extra == 1)
  887. {
  888. p->opt[wr].dist = dist;
  889. dist = MARK_LIT;
  890. }
  891. else
  892. {
  893. p->opt[wr].dist = 0;
  894. len--;
  895. wr--;
  896. p->opt[wr].dist = MARK_LIT;
  897. p->opt[wr].len = 1;
  898. }
  899. }
  900. if (cur == 0)
  901. {
  902. p->backRes = dist;
  903. p->optCur = wr;
  904. return len;
  905. }
  906. wr--;
  907. p->opt[wr].dist = dist;
  908. p->opt[wr].len = (UInt32)len;
  909. }
  910. }
  911. #define LIT_PROBS(pos, prevByte) \
  912. (p->litProbs + (UInt32)3 * (((((pos) << 8) + (prevByte)) & p->lpMask) << p->lc))
  913. static unsigned GetOptimum(CLzmaEnc *p, UInt32 position)
  914. {
  915. unsigned last, cur;
  916. UInt32 reps[LZMA_NUM_REPS];
  917. unsigned repLens[LZMA_NUM_REPS];
  918. UInt32 *matches;
  919. {
  920. UInt32 numAvail;
  921. unsigned numPairs, mainLen, repMaxIndex, i, posState;
  922. UInt32 matchPrice, repMatchPrice;
  923. const Byte *data;
  924. Byte curByte, matchByte;
  925. p->optCur = p->optEnd = 0;
  926. if (p->additionalOffset == 0)
  927. mainLen = ReadMatchDistances(p, &numPairs);
  928. else
  929. {
  930. mainLen = p->longestMatchLen;
  931. numPairs = p->numPairs;
  932. }
  933. numAvail = p->numAvail;
  934. if (numAvail < 2)
  935. {
  936. p->backRes = MARK_LIT;
  937. return 1;
  938. }
  939. if (numAvail > LZMA_MATCH_LEN_MAX)
  940. numAvail = LZMA_MATCH_LEN_MAX;
  941. data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - 1;
  942. repMaxIndex = 0;
  943. for (i = 0; i < LZMA_NUM_REPS; i++)
  944. {
  945. unsigned len;
  946. const Byte *data2;
  947. reps[i] = p->reps[i];
  948. data2 = data - reps[i];
  949. if (data[0] != data2[0] || data[1] != data2[1])
  950. {
  951. repLens[i] = 0;
  952. continue;
  953. }
  954. for (len = 2; len < numAvail && data[len] == data2[len]; len++)
  955. {}
  956. repLens[i] = len;
  957. if (len > repLens[repMaxIndex])
  958. repMaxIndex = i;
  959. }
  960. if (repLens[repMaxIndex] >= p->numFastBytes)
  961. {
  962. unsigned len;
  963. p->backRes = (UInt32)repMaxIndex;
  964. len = repLens[repMaxIndex];
  965. MOVE_POS(p, len - 1)
  966. return len;
  967. }
  968. matches = p->matches;
  969. if (mainLen >= p->numFastBytes)
  970. {
  971. p->backRes = matches[(size_t)numPairs - 1] + LZMA_NUM_REPS;
  972. MOVE_POS(p, mainLen - 1)
  973. return mainLen;
  974. }
  975. curByte = *data;
  976. matchByte = *(data - reps[0]);
  977. last = repLens[repMaxIndex];
  978. if (last <= mainLen)
  979. last = mainLen;
  980. if (last < 2 && curByte != matchByte)
  981. {
  982. p->backRes = MARK_LIT;
  983. return 1;
  984. }
  985. p->opt[0].state = (CState)p->state;
  986. posState = (position & p->pbMask);
  987. {
  988. const CLzmaProb *probs = LIT_PROBS(position, *(data - 1));
  989. p->opt[1].price = GET_PRICE_0(p->isMatch[p->state][posState]) +
  990. (!IsLitState(p->state) ?
  991. LitEnc_Matched_GetPrice(probs, curByte, matchByte, p->ProbPrices) :
  992. LitEnc_GetPrice(probs, curByte, p->ProbPrices));
  993. }
  994. MakeAs_Lit(&p->opt[1]);
  995. matchPrice = GET_PRICE_1(p->isMatch[p->state][posState]);
  996. repMatchPrice = matchPrice + GET_PRICE_1(p->isRep[p->state]);
  997. // 18.06
  998. if (matchByte == curByte && repLens[0] == 0)
  999. {
  1000. UInt32 shortRepPrice = repMatchPrice + GetPrice_ShortRep(p, p->state, posState);
  1001. if (shortRepPrice < p->opt[1].price)
  1002. {
  1003. p->opt[1].price = shortRepPrice;
  1004. MakeAs_ShortRep(&p->opt[1]);
  1005. }
  1006. if (last < 2)
  1007. {
  1008. p->backRes = p->opt[1].dist;
  1009. return 1;
  1010. }
  1011. }
  1012. p->opt[1].len = 1;
  1013. p->opt[0].reps[0] = reps[0];
  1014. p->opt[0].reps[1] = reps[1];
  1015. p->opt[0].reps[2] = reps[2];
  1016. p->opt[0].reps[3] = reps[3];
  1017. // ---------- REP ----------
  1018. for (i = 0; i < LZMA_NUM_REPS; i++)
  1019. {
  1020. unsigned repLen = repLens[i];
  1021. UInt32 price;
  1022. if (repLen < 2)
  1023. continue;
  1024. price = repMatchPrice + GetPrice_PureRep(p, i, p->state, posState);
  1025. do
  1026. {
  1027. UInt32 price2 = price + GET_PRICE_LEN(&p->repLenEnc, posState, repLen);
  1028. COptimal *opt = &p->opt[repLen];
  1029. if (price2 < opt->price)
  1030. {
  1031. opt->price = price2;
  1032. opt->len = (UInt32)repLen;
  1033. opt->dist = (UInt32)i;
  1034. opt->extra = 0;
  1035. }
  1036. }
  1037. while (--repLen >= 2);
  1038. }
  1039. // ---------- MATCH ----------
  1040. {
  1041. unsigned len = repLens[0] + 1;
  1042. if (len <= mainLen)
  1043. {
  1044. unsigned offs = 0;
  1045. UInt32 normalMatchPrice = matchPrice + GET_PRICE_0(p->isRep[p->state]);
  1046. if (len < 2)
  1047. len = 2;
  1048. else
  1049. while (len > matches[offs])
  1050. offs += 2;
  1051. for (; ; len++)
  1052. {
  1053. COptimal *opt;
  1054. UInt32 dist = matches[(size_t)offs + 1];
  1055. UInt32 price = normalMatchPrice + GET_PRICE_LEN(&p->lenEnc, posState, len);
  1056. unsigned lenToPosState = GetLenToPosState(len);
  1057. if (dist < kNumFullDistances)
  1058. price += p->distancesPrices[lenToPosState][dist & (kNumFullDistances - 1)];
  1059. else
  1060. {
  1061. unsigned slot;
  1062. GetPosSlot2(dist, slot);
  1063. price += p->alignPrices[dist & kAlignMask];
  1064. price += p->posSlotPrices[lenToPosState][slot];
  1065. }
  1066. opt = &p->opt[len];
  1067. if (price < opt->price)
  1068. {
  1069. opt->price = price;
  1070. opt->len = (UInt32)len;
  1071. opt->dist = dist + LZMA_NUM_REPS;
  1072. opt->extra = 0;
  1073. }
  1074. if (len == matches[offs])
  1075. {
  1076. offs += 2;
  1077. if (offs == numPairs)
  1078. break;
  1079. }
  1080. }
  1081. }
  1082. }
  1083. cur = 0;
  1084. #ifdef SHOW_STAT2
  1085. /* if (position >= 0) */
  1086. {
  1087. unsigned i;
  1088. printf("\n pos = %4X", position);
  1089. for (i = cur; i <= last; i++)
  1090. printf("\nprice[%4X] = %u", position - cur + i, p->opt[i].price);
  1091. }
  1092. #endif
  1093. }
  1094. // ---------- Optimal Parsing ----------
  1095. for (;;)
  1096. {
  1097. unsigned numAvail;
  1098. UInt32 numAvailFull;
  1099. unsigned newLen, numPairs, prev, state, posState, startLen;
  1100. UInt32 litPrice, matchPrice, repMatchPrice;
  1101. BoolInt nextIsLit;
  1102. Byte curByte, matchByte;
  1103. const Byte *data;
  1104. COptimal *curOpt, *nextOpt;
  1105. if (++cur == last)
  1106. break;
  1107. // 18.06
  1108. if (cur >= kNumOpts - 64)
  1109. {
  1110. unsigned j, best;
  1111. UInt32 price = p->opt[cur].price;
  1112. best = cur;
  1113. for (j = cur + 1; j <= last; j++)
  1114. {
  1115. UInt32 price2 = p->opt[j].price;
  1116. if (price >= price2)
  1117. {
  1118. price = price2;
  1119. best = j;
  1120. }
  1121. }
  1122. {
  1123. unsigned delta = best - cur;
  1124. if (delta != 0)
  1125. {
  1126. MOVE_POS(p, delta);
  1127. }
  1128. }
  1129. cur = best;
  1130. break;
  1131. }
  1132. newLen = ReadMatchDistances(p, &numPairs);
  1133. if (newLen >= p->numFastBytes)
  1134. {
  1135. p->numPairs = numPairs;
  1136. p->longestMatchLen = newLen;
  1137. break;
  1138. }
  1139. curOpt = &p->opt[cur];
  1140. position++;
  1141. // we need that check here, if skip_items in p->opt are possible
  1142. /*
  1143. if (curOpt->price >= kInfinityPrice)
  1144. continue;
  1145. */
  1146. prev = cur - curOpt->len;
  1147. if (curOpt->len == 1)
  1148. {
  1149. state = (unsigned)p->opt[prev].state;
  1150. if (IsShortRep(curOpt))
  1151. state = kShortRepNextStates[state];
  1152. else
  1153. state = kLiteralNextStates[state];
  1154. }
  1155. else
  1156. {
  1157. const COptimal *prevOpt;
  1158. UInt32 b0;
  1159. UInt32 dist = curOpt->dist;
  1160. if (curOpt->extra)
  1161. {
  1162. prev -= (unsigned)curOpt->extra;
  1163. state = kState_RepAfterLit;
  1164. if (curOpt->extra == 1)
  1165. state = (dist < LZMA_NUM_REPS ? kState_RepAfterLit : kState_MatchAfterLit);
  1166. }
  1167. else
  1168. {
  1169. state = (unsigned)p->opt[prev].state;
  1170. if (dist < LZMA_NUM_REPS)
  1171. state = kRepNextStates[state];
  1172. else
  1173. state = kMatchNextStates[state];
  1174. }
  1175. prevOpt = &p->opt[prev];
  1176. b0 = prevOpt->reps[0];
  1177. if (dist < LZMA_NUM_REPS)
  1178. {
  1179. if (dist == 0)
  1180. {
  1181. reps[0] = b0;
  1182. reps[1] = prevOpt->reps[1];
  1183. reps[2] = prevOpt->reps[2];
  1184. reps[3] = prevOpt->reps[3];
  1185. }
  1186. else
  1187. {
  1188. reps[1] = b0;
  1189. b0 = prevOpt->reps[1];
  1190. if (dist == 1)
  1191. {
  1192. reps[0] = b0;
  1193. reps[2] = prevOpt->reps[2];
  1194. reps[3] = prevOpt->reps[3];
  1195. }
  1196. else
  1197. {
  1198. reps[2] = b0;
  1199. reps[0] = prevOpt->reps[dist];
  1200. reps[3] = prevOpt->reps[dist ^ 1];
  1201. }
  1202. }
  1203. }
  1204. else
  1205. {
  1206. reps[0] = (dist - LZMA_NUM_REPS + 1);
  1207. reps[1] = b0;
  1208. reps[2] = prevOpt->reps[1];
  1209. reps[3] = prevOpt->reps[2];
  1210. }
  1211. }
  1212. curOpt->state = (CState)state;
  1213. curOpt->reps[0] = reps[0];
  1214. curOpt->reps[1] = reps[1];
  1215. curOpt->reps[2] = reps[2];
  1216. curOpt->reps[3] = reps[3];
  1217. data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - 1;
  1218. curByte = *data;
  1219. matchByte = *(data - reps[0]);
  1220. posState = (position & p->pbMask);
  1221. /*
  1222. The order of Price checks:
  1223. < LIT
  1224. <= SHORT_REP
  1225. < LIT : REP_0
  1226. < REP [ : LIT : REP_0 ]
  1227. < MATCH [ : LIT : REP_0 ]
  1228. */
  1229. {
  1230. UInt32 curPrice = curOpt->price;
  1231. unsigned prob = p->isMatch[state][posState];
  1232. matchPrice = curPrice + GET_PRICE_1(prob);
  1233. litPrice = curPrice + GET_PRICE_0(prob);
  1234. }
  1235. nextOpt = &p->opt[(size_t)cur + 1];
  1236. nextIsLit = False;
  1237. // here we can allow skip_items in p->opt, if we don't check (nextOpt->price < kInfinityPrice)
  1238. // 18.new.06
  1239. if ((nextOpt->price < kInfinityPrice
  1240. // && !IsLitState(state)
  1241. && matchByte == curByte)
  1242. || litPrice > nextOpt->price
  1243. )
  1244. litPrice = 0;
  1245. else
  1246. {
  1247. const CLzmaProb *probs = LIT_PROBS(position, *(data - 1));
  1248. litPrice += (!IsLitState(state) ?
  1249. LitEnc_Matched_GetPrice(probs, curByte, matchByte, p->ProbPrices) :
  1250. LitEnc_GetPrice(probs, curByte, p->ProbPrices));
  1251. if (litPrice < nextOpt->price)
  1252. {
  1253. nextOpt->price = litPrice;
  1254. nextOpt->len = 1;
  1255. MakeAs_Lit(nextOpt);
  1256. nextIsLit = True;
  1257. }
  1258. }
  1259. repMatchPrice = matchPrice + GET_PRICE_1(p->isRep[state]);
  1260. numAvailFull = p->numAvail;
  1261. {
  1262. unsigned temp = kNumOpts - 1 - cur;
  1263. if (numAvailFull > temp)
  1264. numAvailFull = (UInt32)temp;
  1265. }
  1266. // 18.06
  1267. // ---------- SHORT_REP ----------
  1268. if (IsLitState(state)) // 18.new
  1269. if (matchByte == curByte)
  1270. if (repMatchPrice < nextOpt->price) // 18.new
  1271. // if (numAvailFull < 2 || data[1] != *(data - reps[0] + 1))
  1272. if (
  1273. // nextOpt->price >= kInfinityPrice ||
  1274. nextOpt->len < 2 // we can check nextOpt->len, if skip items are not allowed in p->opt
  1275. || (nextOpt->dist != 0
  1276. // && nextOpt->extra <= 1 // 17.old
  1277. )
  1278. )
  1279. {
  1280. UInt32 shortRepPrice = repMatchPrice + GetPrice_ShortRep(p, state, posState);
  1281. // if (shortRepPrice <= nextOpt->price) // 17.old
  1282. if (shortRepPrice < nextOpt->price) // 18.new
  1283. {
  1284. nextOpt->price = shortRepPrice;
  1285. nextOpt->len = 1;
  1286. MakeAs_ShortRep(nextOpt);
  1287. nextIsLit = False;
  1288. }
  1289. }
  1290. if (numAvailFull < 2)
  1291. continue;
  1292. numAvail = (numAvailFull <= p->numFastBytes ? numAvailFull : p->numFastBytes);
  1293. // numAvail <= p->numFastBytes
  1294. // ---------- LIT : REP_0 ----------
  1295. if (!nextIsLit
  1296. && litPrice != 0 // 18.new
  1297. && matchByte != curByte
  1298. && numAvailFull > 2)
  1299. {
  1300. const Byte *data2 = data - reps[0];
  1301. if (data[1] == data2[1] && data[2] == data2[2])
  1302. {
  1303. unsigned len;
  1304. unsigned limit = p->numFastBytes + 1;
  1305. if (limit > numAvailFull)
  1306. limit = numAvailFull;
  1307. for (len = 3; len < limit && data[len] == data2[len]; len++)
  1308. {}
  1309. {
  1310. unsigned state2 = kLiteralNextStates[state];
  1311. unsigned posState2 = (position + 1) & p->pbMask;
  1312. UInt32 price = litPrice + GetPrice_Rep_0(p, state2, posState2);
  1313. {
  1314. unsigned offset = cur + len;
  1315. if (last < offset)
  1316. last = offset;
  1317. // do
  1318. {
  1319. UInt32 price2;
  1320. COptimal *opt;
  1321. len--;
  1322. // price2 = price + GetPrice_Len_Rep_0(p, len, state2, posState2);
  1323. price2 = price + GET_PRICE_LEN(&p->repLenEnc, posState2, len);
  1324. opt = &p->opt[offset];
  1325. // offset--;
  1326. if (price2 < opt->price)
  1327. {
  1328. opt->price = price2;
  1329. opt->len = (UInt32)len;
  1330. opt->dist = 0;
  1331. opt->extra = 1;
  1332. }
  1333. }
  1334. // while (len >= 3);
  1335. }
  1336. }
  1337. }
  1338. }
  1339. startLen = 2; /* speed optimization */
  1340. {
  1341. // ---------- REP ----------
  1342. unsigned repIndex = 0; // 17.old
  1343. // unsigned repIndex = IsLitState(state) ? 0 : 1; // 18.notused
  1344. for (; repIndex < LZMA_NUM_REPS; repIndex++)
  1345. {
  1346. unsigned len;
  1347. UInt32 price;
  1348. const Byte *data2 = data - reps[repIndex];
  1349. if (data[0] != data2[0] || data[1] != data2[1])
  1350. continue;
  1351. for (len = 2; len < numAvail && data[len] == data2[len]; len++)
  1352. {}
  1353. // if (len < startLen) continue; // 18.new: speed optimization
  1354. {
  1355. unsigned offset = cur + len;
  1356. if (last < offset)
  1357. last = offset;
  1358. }
  1359. {
  1360. unsigned len2 = len;
  1361. price = repMatchPrice + GetPrice_PureRep(p, repIndex, state, posState);
  1362. do
  1363. {
  1364. UInt32 price2 = price + GET_PRICE_LEN(&p->repLenEnc, posState, len2);
  1365. COptimal *opt = &p->opt[cur + len2];
  1366. if (price2 < opt->price)
  1367. {
  1368. opt->price = price2;
  1369. opt->len = (UInt32)len2;
  1370. opt->dist = (UInt32)repIndex;
  1371. opt->extra = 0;
  1372. }
  1373. }
  1374. while (--len2 >= 2);
  1375. }
  1376. if (repIndex == 0) startLen = len + 1; // 17.old
  1377. // startLen = len + 1; // 18.new
  1378. /* if (_maxMode) */
  1379. {
  1380. // ---------- REP : LIT : REP_0 ----------
  1381. // numFastBytes + 1 + numFastBytes
  1382. unsigned len2 = len + 1;
  1383. unsigned limit = len2 + p->numFastBytes;
  1384. if (limit > numAvailFull)
  1385. limit = numAvailFull;
  1386. len2 += 2;
  1387. if (len2 <= limit)
  1388. if (data[len2 - 2] == data2[len2 - 2])
  1389. if (data[len2 - 1] == data2[len2 - 1])
  1390. {
  1391. unsigned state2 = kRepNextStates[state];
  1392. unsigned posState2 = (position + len) & p->pbMask;
  1393. price += GET_PRICE_LEN(&p->repLenEnc, posState, len)
  1394. + GET_PRICE_0(p->isMatch[state2][posState2])
  1395. + LitEnc_Matched_GetPrice(LIT_PROBS(position + len, data[(size_t)len - 1]),
  1396. data[len], data2[len], p->ProbPrices);
  1397. // state2 = kLiteralNextStates[state2];
  1398. state2 = kState_LitAfterRep;
  1399. posState2 = (posState2 + 1) & p->pbMask;
  1400. price += GetPrice_Rep_0(p, state2, posState2);
  1401. for (; len2 < limit && data[len2] == data2[len2]; len2++)
  1402. {}
  1403. len2 -= len;
  1404. // if (len2 >= 3)
  1405. {
  1406. {
  1407. unsigned offset = cur + len + len2;
  1408. if (last < offset)
  1409. last = offset;
  1410. // do
  1411. {
  1412. UInt32 price2;
  1413. COptimal *opt;
  1414. len2--;
  1415. // price2 = price + GetPrice_Len_Rep_0(p, len2, state2, posState2);
  1416. price2 = price + GET_PRICE_LEN(&p->repLenEnc, posState2, len2);
  1417. opt = &p->opt[offset];
  1418. // offset--;
  1419. if (price2 < opt->price)
  1420. {
  1421. opt->price = price2;
  1422. opt->len = (UInt32)len2;
  1423. opt->extra = (CExtra)(len + 1);
  1424. opt->dist = (UInt32)repIndex;
  1425. }
  1426. }
  1427. // while (len2 >= 3);
  1428. }
  1429. }
  1430. }
  1431. }
  1432. }
  1433. }
  1434. // ---------- MATCH ----------
  1435. /* for (unsigned len = 2; len <= newLen; len++) */
  1436. if (newLen > numAvail)
  1437. {
  1438. newLen = numAvail;
  1439. for (numPairs = 0; newLen > matches[numPairs]; numPairs += 2);
  1440. matches[numPairs] = (UInt32)newLen;
  1441. numPairs += 2;
  1442. }
  1443. // startLen = 2; /* speed optimization */
  1444. if (newLen >= startLen)
  1445. {
  1446. UInt32 normalMatchPrice = matchPrice + GET_PRICE_0(p->isRep[state]);
  1447. UInt32 dist;
  1448. unsigned offs, posSlot, len;
  1449. {
  1450. unsigned offset = cur + newLen;
  1451. if (last < offset)
  1452. last = offset;
  1453. }
  1454. offs = 0;
  1455. while (startLen > matches[offs])
  1456. offs += 2;
  1457. dist = matches[(size_t)offs + 1];
  1458. // if (dist >= kNumFullDistances)
  1459. GetPosSlot2(dist, posSlot);
  1460. for (len = /*2*/ startLen; ; len++)
  1461. {
  1462. UInt32 price = normalMatchPrice + GET_PRICE_LEN(&p->lenEnc, posState, len);
  1463. {
  1464. COptimal *opt;
  1465. unsigned lenNorm = len - 2;
  1466. lenNorm = GetLenToPosState2(lenNorm);
  1467. if (dist < kNumFullDistances)
  1468. price += p->distancesPrices[lenNorm][dist & (kNumFullDistances - 1)];
  1469. else
  1470. price += p->posSlotPrices[lenNorm][posSlot] + p->alignPrices[dist & kAlignMask];
  1471. opt = &p->opt[cur + len];
  1472. if (price < opt->price)
  1473. {
  1474. opt->price = price;
  1475. opt->len = (UInt32)len;
  1476. opt->dist = dist + LZMA_NUM_REPS;
  1477. opt->extra = 0;
  1478. }
  1479. }
  1480. if (len == matches[offs])
  1481. {
  1482. // if (p->_maxMode) {
  1483. // MATCH : LIT : REP_0
  1484. const Byte *data2 = data - dist - 1;
  1485. unsigned len2 = len + 1;
  1486. unsigned limit = len2 + p->numFastBytes;
  1487. if (limit > numAvailFull)
  1488. limit = numAvailFull;
  1489. len2 += 2;
  1490. if (len2 <= limit)
  1491. if (data[len2 - 2] == data2[len2 - 2])
  1492. if (data[len2 - 1] == data2[len2 - 1])
  1493. {
  1494. for (; len2 < limit && data[len2] == data2[len2]; len2++)
  1495. {}
  1496. len2 -= len;
  1497. // if (len2 >= 3)
  1498. {
  1499. unsigned state2 = kMatchNextStates[state];
  1500. unsigned posState2 = (position + len) & p->pbMask;
  1501. unsigned offset;
  1502. price += GET_PRICE_0(p->isMatch[state2][posState2]);
  1503. price += LitEnc_Matched_GetPrice(LIT_PROBS(position + len, data[(size_t)len - 1]),
  1504. data[len], data2[len], p->ProbPrices);
  1505. // state2 = kLiteralNextStates[state2];
  1506. state2 = kState_LitAfterMatch;
  1507. posState2 = (posState2 + 1) & p->pbMask;
  1508. price += GetPrice_Rep_0(p, state2, posState2);
  1509. offset = cur + len + len2;
  1510. if (last < offset)
  1511. last = offset;
  1512. // do
  1513. {
  1514. UInt32 price2;
  1515. COptimal *opt;
  1516. len2--;
  1517. // price2 = price + GetPrice_Len_Rep_0(p, len2, state2, posState2);
  1518. price2 = price + GET_PRICE_LEN(&p->repLenEnc, posState2, len2);
  1519. opt = &p->opt[offset];
  1520. // offset--;
  1521. if (price2 < opt->price)
  1522. {
  1523. opt->price = price2;
  1524. opt->len = (UInt32)len2;
  1525. opt->extra = (CExtra)(len + 1);
  1526. opt->dist = dist + LZMA_NUM_REPS;
  1527. }
  1528. }
  1529. // while (len2 >= 3);
  1530. }
  1531. }
  1532. offs += 2;
  1533. if (offs == numPairs)
  1534. break;
  1535. dist = matches[(size_t)offs + 1];
  1536. // if (dist >= kNumFullDistances)
  1537. GetPosSlot2(dist, posSlot);
  1538. }
  1539. }
  1540. }
  1541. }
  1542. do
  1543. p->opt[last].price = kInfinityPrice;
  1544. while (--last);
  1545. return Backward(p, cur);
  1546. }
  1547. #define ChangePair(smallDist, bigDist) (((bigDist) >> 7) > (smallDist))
  1548. static unsigned GetOptimumFast(CLzmaEnc *p)
  1549. {
  1550. UInt32 numAvail, mainDist;
  1551. unsigned mainLen, numPairs, repIndex, repLen, i;
  1552. const Byte *data;
  1553. if (p->additionalOffset == 0)
  1554. mainLen = ReadMatchDistances(p, &numPairs);
  1555. else
  1556. {
  1557. mainLen = p->longestMatchLen;
  1558. numPairs = p->numPairs;
  1559. }
  1560. numAvail = p->numAvail;
  1561. p->backRes = MARK_LIT;
  1562. if (numAvail < 2)
  1563. return 1;
  1564. // if (mainLen < 2 && p->state == 0) return 1; // 18.06.notused
  1565. if (numAvail > LZMA_MATCH_LEN_MAX)
  1566. numAvail = LZMA_MATCH_LEN_MAX;
  1567. data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - 1;
  1568. repLen = repIndex = 0;
  1569. for (i = 0; i < LZMA_NUM_REPS; i++)
  1570. {
  1571. unsigned len;
  1572. const Byte *data2 = data - p->reps[i];
  1573. if (data[0] != data2[0] || data[1] != data2[1])
  1574. continue;
  1575. for (len = 2; len < numAvail && data[len] == data2[len]; len++)
  1576. {}
  1577. if (len >= p->numFastBytes)
  1578. {
  1579. p->backRes = (UInt32)i;
  1580. MOVE_POS(p, len - 1)
  1581. return len;
  1582. }
  1583. if (len > repLen)
  1584. {
  1585. repIndex = i;
  1586. repLen = len;
  1587. }
  1588. }
  1589. if (mainLen >= p->numFastBytes)
  1590. {
  1591. p->backRes = p->matches[(size_t)numPairs - 1] + LZMA_NUM_REPS;
  1592. MOVE_POS(p, mainLen - 1)
  1593. return mainLen;
  1594. }
  1595. mainDist = 0; /* for GCC */
  1596. if (mainLen >= 2)
  1597. {
  1598. mainDist = p->matches[(size_t)numPairs - 1];
  1599. while (numPairs > 2)
  1600. {
  1601. UInt32 dist2;
  1602. if (mainLen != p->matches[(size_t)numPairs - 4] + 1)
  1603. break;
  1604. dist2 = p->matches[(size_t)numPairs - 3];
  1605. if (!ChangePair(dist2, mainDist))
  1606. break;
  1607. numPairs -= 2;
  1608. mainLen--;
  1609. mainDist = dist2;
  1610. }
  1611. if (mainLen == 2 && mainDist >= 0x80)
  1612. mainLen = 1;
  1613. }
  1614. if (repLen >= 2)
  1615. if ( repLen + 1 >= mainLen
  1616. || (repLen + 2 >= mainLen && mainDist >= (1 << 9))
  1617. || (repLen + 3 >= mainLen && mainDist >= (1 << 15)))
  1618. {
  1619. p->backRes = (UInt32)repIndex;
  1620. MOVE_POS(p, repLen - 1)
  1621. return repLen;
  1622. }
  1623. if (mainLen < 2 || numAvail <= 2)
  1624. return 1;
  1625. {
  1626. unsigned len1 = ReadMatchDistances(p, &p->numPairs);
  1627. p->longestMatchLen = len1;
  1628. if (len1 >= 2)
  1629. {
  1630. UInt32 newDist = p->matches[(size_t)p->numPairs - 1];
  1631. if ( (len1 >= mainLen && newDist < mainDist)
  1632. || (len1 == mainLen + 1 && !ChangePair(mainDist, newDist))
  1633. || (len1 > mainLen + 1)
  1634. || (len1 + 1 >= mainLen && mainLen >= 3 && ChangePair(newDist, mainDist)))
  1635. return 1;
  1636. }
  1637. }
  1638. data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - 1;
  1639. for (i = 0; i < LZMA_NUM_REPS; i++)
  1640. {
  1641. unsigned len, limit;
  1642. const Byte *data2 = data - p->reps[i];
  1643. if (data[0] != data2[0] || data[1] != data2[1])
  1644. continue;
  1645. limit = mainLen - 1;
  1646. for (len = 2;; len++)
  1647. {
  1648. if (len >= limit)
  1649. return 1;
  1650. if (data[len] != data2[len])
  1651. break;
  1652. }
  1653. }
  1654. p->backRes = mainDist + LZMA_NUM_REPS;
  1655. if (mainLen != 2)
  1656. {
  1657. MOVE_POS(p, mainLen - 2)
  1658. }
  1659. return mainLen;
  1660. }
  1661. static void WriteEndMarker(CLzmaEnc *p, unsigned posState)
  1662. {
  1663. UInt32 range;
  1664. range = p->rc.range;
  1665. {
  1666. UInt32 ttt, newBound;
  1667. CLzmaProb *prob = &p->isMatch[p->state][posState];
  1668. RC_BIT_PRE(&p->rc, prob)
  1669. RC_BIT_1(&p->rc, prob)
  1670. prob = &p->isRep[p->state];
  1671. RC_BIT_PRE(&p->rc, prob)
  1672. RC_BIT_0(&p->rc, prob)
  1673. }
  1674. p->state = kMatchNextStates[p->state];
  1675. p->rc.range = range;
  1676. LenEnc_Encode(&p->lenProbs, &p->rc, 0, posState);
  1677. range = p->rc.range;
  1678. {
  1679. // RcTree_Encode_PosSlot(&p->rc, p->posSlotEncoder[0], (1 << kNumPosSlotBits) - 1);
  1680. CLzmaProb *probs = p->posSlotEncoder[0];
  1681. unsigned m = 1;
  1682. do
  1683. {
  1684. UInt32 ttt, newBound;
  1685. RC_BIT_PRE(p, probs + m)
  1686. RC_BIT_1(&p->rc, probs + m);
  1687. m = (m << 1) + 1;
  1688. }
  1689. while (m < (1 << kNumPosSlotBits));
  1690. }
  1691. {
  1692. // RangeEnc_EncodeDirectBits(&p->rc, ((UInt32)1 << (30 - kNumAlignBits)) - 1, 30 - kNumAlignBits); UInt32 range = p->range;
  1693. unsigned numBits = 30 - kNumAlignBits;
  1694. do
  1695. {
  1696. range >>= 1;
  1697. p->rc.low += range;
  1698. RC_NORM(&p->rc)
  1699. }
  1700. while (--numBits);
  1701. }
  1702. {
  1703. // RcTree_ReverseEncode(&p->rc, p->posAlignEncoder, kNumAlignBits, kAlignMask);
  1704. CLzmaProb *probs = p->posAlignEncoder;
  1705. unsigned m = 1;
  1706. do
  1707. {
  1708. UInt32 ttt, newBound;
  1709. RC_BIT_PRE(p, probs + m)
  1710. RC_BIT_1(&p->rc, probs + m);
  1711. m = (m << 1) + 1;
  1712. }
  1713. while (m < kAlignTableSize);
  1714. }
  1715. p->rc.range = range;
  1716. }
  1717. static SRes CheckErrors(CLzmaEnc *p)
  1718. {
  1719. if (p->result != SZ_OK)
  1720. return p->result;
  1721. if (p->rc.res != SZ_OK)
  1722. p->result = SZ_ERROR_WRITE;
  1723. if (p->matchFinderBase.result != SZ_OK)
  1724. p->result = SZ_ERROR_READ;
  1725. if (p->result != SZ_OK)
  1726. p->finished = True;
  1727. return p->result;
  1728. }
  1729. MY_NO_INLINE static SRes Flush(CLzmaEnc *p, UInt32 nowPos)
  1730. {
  1731. /* ReleaseMFStream(); */
  1732. p->finished = True;
  1733. if (p->writeEndMark)
  1734. WriteEndMarker(p, nowPos & p->pbMask);
  1735. RangeEnc_FlushData(&p->rc);
  1736. RangeEnc_FlushStream(&p->rc);
  1737. return CheckErrors(p);
  1738. }
  1739. MY_NO_INLINE static void FillAlignPrices(CLzmaEnc *p)
  1740. {
  1741. unsigned i;
  1742. const CProbPrice *ProbPrices = p->ProbPrices;
  1743. const CLzmaProb *probs = p->posAlignEncoder;
  1744. // p->alignPriceCount = 0;
  1745. for (i = 0; i < kAlignTableSize / 2; i++)
  1746. {
  1747. UInt32 price = 0;
  1748. unsigned sym = i;
  1749. unsigned m = 1;
  1750. unsigned bit;
  1751. UInt32 prob;
  1752. bit = sym & 1; sym >>= 1; price += GET_PRICEa(probs[m], bit); m = (m << 1) + bit;
  1753. bit = sym & 1; sym >>= 1; price += GET_PRICEa(probs[m], bit); m = (m << 1) + bit;
  1754. bit = sym & 1; sym >>= 1; price += GET_PRICEa(probs[m], bit); m = (m << 1) + bit;
  1755. prob = probs[m];
  1756. p->alignPrices[i ] = price + GET_PRICEa_0(prob);
  1757. p->alignPrices[i + 8] = price + GET_PRICEa_1(prob);
  1758. // p->alignPrices[i] = RcTree_ReverseGetPrice(p->posAlignEncoder, kNumAlignBits, i, p->ProbPrices);
  1759. }
  1760. }
  1761. MY_NO_INLINE static void FillDistancesPrices(CLzmaEnc *p)
  1762. {
  1763. // int y; for (y = 0; y < 100; y++) {
  1764. UInt32 tempPrices[kNumFullDistances];
  1765. unsigned i, lps;
  1766. const CProbPrice *ProbPrices = p->ProbPrices;
  1767. p->matchPriceCount = 0;
  1768. for (i = kStartPosModelIndex / 2; i < kNumFullDistances / 2; i++)
  1769. {
  1770. unsigned posSlot = GetPosSlot1(i);
  1771. unsigned footerBits = (posSlot >> 1) - 1;
  1772. unsigned base = ((2 | (posSlot & 1)) << footerBits);
  1773. const CLzmaProb *probs = p->posEncoders + (size_t)base * 2;
  1774. // tempPrices[i] = RcTree_ReverseGetPrice(p->posEncoders + base, footerBits, i - base, p->ProbPrices);
  1775. UInt32 price = 0;
  1776. unsigned m = 1;
  1777. unsigned sym = i;
  1778. unsigned offset = (unsigned)1 << footerBits;
  1779. base += i;
  1780. if (footerBits)
  1781. do
  1782. {
  1783. unsigned bit = sym & 1;
  1784. sym >>= 1;
  1785. price += GET_PRICEa(probs[m], bit);
  1786. m = (m << 1) + bit;
  1787. }
  1788. while (--footerBits);
  1789. {
  1790. unsigned prob = probs[m];
  1791. tempPrices[base ] = price + GET_PRICEa_0(prob);
  1792. tempPrices[base + offset] = price + GET_PRICEa_1(prob);
  1793. }
  1794. }
  1795. for (lps = 0; lps < kNumLenToPosStates; lps++)
  1796. {
  1797. unsigned slot;
  1798. unsigned distTableSize2 = (p->distTableSize + 1) >> 1;
  1799. UInt32 *posSlotPrices = p->posSlotPrices[lps];
  1800. const CLzmaProb *probs = p->posSlotEncoder[lps];
  1801. for (slot = 0; slot < distTableSize2; slot++)
  1802. {
  1803. // posSlotPrices[slot] = RcTree_GetPrice(encoder, kNumPosSlotBits, slot, p->ProbPrices);
  1804. UInt32 price;
  1805. unsigned bit;
  1806. unsigned sym = slot + (1 << (kNumPosSlotBits - 1));
  1807. unsigned prob;
  1808. bit = sym & 1; sym >>= 1; price = GET_PRICEa(probs[sym], bit);
  1809. bit = sym & 1; sym >>= 1; price += GET_PRICEa(probs[sym], bit);
  1810. bit = sym & 1; sym >>= 1; price += GET_PRICEa(probs[sym], bit);
  1811. bit = sym & 1; sym >>= 1; price += GET_PRICEa(probs[sym], bit);
  1812. bit = sym & 1; sym >>= 1; price += GET_PRICEa(probs[sym], bit);
  1813. prob = probs[(size_t)slot + (1 << (kNumPosSlotBits - 1))];
  1814. posSlotPrices[(size_t)slot * 2 ] = price + GET_PRICEa_0(prob);
  1815. posSlotPrices[(size_t)slot * 2 + 1] = price + GET_PRICEa_1(prob);
  1816. }
  1817. {
  1818. UInt32 delta = ((UInt32)((kEndPosModelIndex / 2 - 1) - kNumAlignBits) << kNumBitPriceShiftBits);
  1819. for (slot = kEndPosModelIndex / 2; slot < distTableSize2; slot++)
  1820. {
  1821. posSlotPrices[(size_t)slot * 2 ] += delta;
  1822. posSlotPrices[(size_t)slot * 2 + 1] += delta;
  1823. delta += ((UInt32)1 << kNumBitPriceShiftBits);
  1824. }
  1825. }
  1826. {
  1827. UInt32 *dp = p->distancesPrices[lps];
  1828. dp[0] = posSlotPrices[0];
  1829. dp[1] = posSlotPrices[1];
  1830. dp[2] = posSlotPrices[2];
  1831. dp[3] = posSlotPrices[3];
  1832. for (i = 4; i < kNumFullDistances; i += 2)
  1833. {
  1834. UInt32 slotPrice = posSlotPrices[GetPosSlot1(i)];
  1835. dp[i ] = slotPrice + tempPrices[i];
  1836. dp[i + 1] = slotPrice + tempPrices[i + 1];
  1837. }
  1838. }
  1839. }
  1840. // }
  1841. }
  1842. void LzmaEnc_Construct(CLzmaEnc *p)
  1843. {
  1844. RangeEnc_Construct(&p->rc);
  1845. MatchFinder_Construct(&p->matchFinderBase);
  1846. #ifndef _7ZIP_ST
  1847. MatchFinderMt_Construct(&p->matchFinderMt);
  1848. p->matchFinderMt.MatchFinder = &p->matchFinderBase;
  1849. #endif
  1850. {
  1851. CLzmaEncProps props;
  1852. LzmaEncProps_Init(&props);
  1853. LzmaEnc_SetProps(p, &props);
  1854. }
  1855. #ifndef LZMA_LOG_BSR
  1856. LzmaEnc_FastPosInit(p->g_FastPos);
  1857. #endif
  1858. LzmaEnc_InitPriceTables(p->ProbPrices);
  1859. p->litProbs = NULL;
  1860. p->saveState.litProbs = NULL;
  1861. }
  1862. CLzmaEncHandle LzmaEnc_Create(ISzAllocPtr alloc)
  1863. {
  1864. void *p;
  1865. p = ISzAlloc_Alloc(alloc, sizeof(CLzmaEnc));
  1866. if (p)
  1867. LzmaEnc_Construct((CLzmaEnc *)p);
  1868. return p;
  1869. }
  1870. void LzmaEnc_FreeLits(CLzmaEnc *p, ISzAllocPtr alloc)
  1871. {
  1872. ISzAlloc_Free(alloc, p->litProbs);
  1873. ISzAlloc_Free(alloc, p->saveState.litProbs);
  1874. p->litProbs = NULL;
  1875. p->saveState.litProbs = NULL;
  1876. }
  1877. void LzmaEnc_Destruct(CLzmaEnc *p, ISzAllocPtr alloc, ISzAllocPtr allocBig)
  1878. {
  1879. #ifndef _7ZIP_ST
  1880. MatchFinderMt_Destruct(&p->matchFinderMt, allocBig);
  1881. #endif
  1882. MatchFinder_Free(&p->matchFinderBase, allocBig);
  1883. LzmaEnc_FreeLits(p, alloc);
  1884. RangeEnc_Free(&p->rc, alloc);
  1885. }
  1886. void LzmaEnc_Destroy(CLzmaEncHandle p, ISzAllocPtr alloc, ISzAllocPtr allocBig)
  1887. {
  1888. LzmaEnc_Destruct((CLzmaEnc *)p, alloc, allocBig);
  1889. ISzAlloc_Free(alloc, p);
  1890. }
  1891. SRes LzmaEnc_CodeOneBlock(CLzmaEncHandle pp, UInt32 maxPackSize, UInt32 maxUnpackSize)
  1892. {
  1893. CLzmaEnc *p = (CLzmaEnc *) pp;
  1894. UInt32 nowPos32, startPos32;
  1895. if (p->needInit)
  1896. {
  1897. p->matchFinder.Init(p->matchFinderObj);
  1898. p->needInit = 0;
  1899. }
  1900. if (p->finished)
  1901. return p->result;
  1902. RINOK(CheckErrors(p));
  1903. nowPos32 = (UInt32)p->nowPos64;
  1904. startPos32 = nowPos32;
  1905. if (p->nowPos64 == 0)
  1906. {
  1907. unsigned numPairs;
  1908. Byte curByte;
  1909. if (p->matchFinder.GetNumAvailableBytes(p->matchFinderObj) == 0)
  1910. return Flush(p, nowPos32);
  1911. ReadMatchDistances(p, &numPairs);
  1912. RangeEnc_EncodeBit_0(&p->rc, &p->isMatch[kState_Start][0]);
  1913. // p->state = kLiteralNextStates[p->state];
  1914. curByte = *(p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - p->additionalOffset);
  1915. LitEnc_Encode(&p->rc, p->litProbs, curByte);
  1916. p->additionalOffset--;
  1917. nowPos32++;
  1918. }
  1919. if (p->matchFinder.GetNumAvailableBytes(p->matchFinderObj) != 0)
  1920. for (;;)
  1921. {
  1922. UInt32 dist;
  1923. unsigned len, posState;
  1924. UInt32 range, ttt, newBound;
  1925. CLzmaProb *probs;
  1926. if (p->fastMode)
  1927. len = GetOptimumFast(p);
  1928. else
  1929. {
  1930. unsigned oci = p->optCur;
  1931. if (p->optEnd == oci)
  1932. len = GetOptimum(p, nowPos32);
  1933. else
  1934. {
  1935. const COptimal *opt = &p->opt[oci];
  1936. len = opt->len;
  1937. p->backRes = opt->dist;
  1938. p->optCur = oci + 1;
  1939. }
  1940. }
  1941. posState = (unsigned)nowPos32 & p->pbMask;
  1942. range = p->rc.range;
  1943. probs = &p->isMatch[p->state][posState];
  1944. RC_BIT_PRE(&p->rc, probs)
  1945. dist = p->backRes;
  1946. #ifdef SHOW_STAT2
  1947. printf("\n pos = %6X, len = %3u pos = %6u", nowPos32, len, dist);
  1948. #endif
  1949. if (dist == MARK_LIT)
  1950. {
  1951. Byte curByte;
  1952. const Byte *data;
  1953. unsigned state;
  1954. RC_BIT_0(&p->rc, probs);
  1955. p->rc.range = range;
  1956. data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - p->additionalOffset;
  1957. probs = LIT_PROBS(nowPos32, *(data - 1));
  1958. curByte = *data;
  1959. state = p->state;
  1960. p->state = kLiteralNextStates[state];
  1961. if (IsLitState(state))
  1962. LitEnc_Encode(&p->rc, probs, curByte);
  1963. else
  1964. LitEnc_EncodeMatched(&p->rc, probs, curByte, *(data - p->reps[0]));
  1965. }
  1966. else
  1967. {
  1968. RC_BIT_1(&p->rc, probs);
  1969. probs = &p->isRep[p->state];
  1970. RC_BIT_PRE(&p->rc, probs)
  1971. if (dist < LZMA_NUM_REPS)
  1972. {
  1973. RC_BIT_1(&p->rc, probs);
  1974. probs = &p->isRepG0[p->state];
  1975. RC_BIT_PRE(&p->rc, probs)
  1976. if (dist == 0)
  1977. {
  1978. RC_BIT_0(&p->rc, probs);
  1979. probs = &p->isRep0Long[p->state][posState];
  1980. RC_BIT_PRE(&p->rc, probs)
  1981. if (len != 1)
  1982. {
  1983. RC_BIT_1_BASE(&p->rc, probs);
  1984. }
  1985. else
  1986. {
  1987. RC_BIT_0_BASE(&p->rc, probs);
  1988. p->state = kShortRepNextStates[p->state];
  1989. }
  1990. }
  1991. else
  1992. {
  1993. RC_BIT_1(&p->rc, probs);
  1994. probs = &p->isRepG1[p->state];
  1995. RC_BIT_PRE(&p->rc, probs)
  1996. if (dist == 1)
  1997. {
  1998. RC_BIT_0_BASE(&p->rc, probs);
  1999. dist = p->reps[1];
  2000. }
  2001. else
  2002. {
  2003. RC_BIT_1(&p->rc, probs);
  2004. probs = &p->isRepG2[p->state];
  2005. RC_BIT_PRE(&p->rc, probs)
  2006. if (dist == 2)
  2007. {
  2008. RC_BIT_0_BASE(&p->rc, probs);
  2009. dist = p->reps[2];
  2010. }
  2011. else
  2012. {
  2013. RC_BIT_1_BASE(&p->rc, probs);
  2014. dist = p->reps[3];
  2015. p->reps[3] = p->reps[2];
  2016. }
  2017. p->reps[2] = p->reps[1];
  2018. }
  2019. p->reps[1] = p->reps[0];
  2020. p->reps[0] = dist;
  2021. }
  2022. RC_NORM(&p->rc)
  2023. p->rc.range = range;
  2024. if (len != 1)
  2025. {
  2026. LenEnc_Encode(&p->repLenProbs, &p->rc, len - LZMA_MATCH_LEN_MIN, posState);
  2027. --p->repLenEncCounter;
  2028. p->state = kRepNextStates[p->state];
  2029. }
  2030. }
  2031. else
  2032. {
  2033. unsigned posSlot;
  2034. RC_BIT_0(&p->rc, probs);
  2035. p->rc.range = range;
  2036. p->state = kMatchNextStates[p->state];
  2037. LenEnc_Encode(&p->lenProbs, &p->rc, len - LZMA_MATCH_LEN_MIN, posState);
  2038. // --p->lenEnc.counter;
  2039. dist -= LZMA_NUM_REPS;
  2040. p->reps[3] = p->reps[2];
  2041. p->reps[2] = p->reps[1];
  2042. p->reps[1] = p->reps[0];
  2043. p->reps[0] = dist + 1;
  2044. p->matchPriceCount++;
  2045. GetPosSlot(dist, posSlot);
  2046. // RcTree_Encode_PosSlot(&p->rc, p->posSlotEncoder[GetLenToPosState(len)], posSlot);
  2047. {
  2048. UInt32 sym = (UInt32)posSlot + (1 << kNumPosSlotBits);
  2049. range = p->rc.range;
  2050. probs = p->posSlotEncoder[GetLenToPosState(len)];
  2051. do
  2052. {
  2053. CLzmaProb *prob = probs + (sym >> kNumPosSlotBits);
  2054. UInt32 bit = (sym >> (kNumPosSlotBits - 1)) & 1;
  2055. sym <<= 1;
  2056. RC_BIT(&p->rc, prob, bit);
  2057. }
  2058. while (sym < (1 << kNumPosSlotBits * 2));
  2059. p->rc.range = range;
  2060. }
  2061. if (dist >= kStartPosModelIndex)
  2062. {
  2063. unsigned footerBits = ((posSlot >> 1) - 1);
  2064. if (dist < kNumFullDistances)
  2065. {
  2066. unsigned base = ((2 | (posSlot & 1)) << footerBits);
  2067. RcTree_ReverseEncode(&p->rc, p->posEncoders + base, footerBits, (unsigned)(dist /* - base */));
  2068. }
  2069. else
  2070. {
  2071. UInt32 pos2 = (dist | 0xF) << (32 - footerBits);
  2072. range = p->rc.range;
  2073. // RangeEnc_EncodeDirectBits(&p->rc, posReduced >> kNumAlignBits, footerBits - kNumAlignBits);
  2074. /*
  2075. do
  2076. {
  2077. range >>= 1;
  2078. p->rc.low += range & (0 - ((dist >> --footerBits) & 1));
  2079. RC_NORM(&p->rc)
  2080. }
  2081. while (footerBits > kNumAlignBits);
  2082. */
  2083. do
  2084. {
  2085. range >>= 1;
  2086. p->rc.low += range & (0 - (pos2 >> 31));
  2087. pos2 += pos2;
  2088. RC_NORM(&p->rc)
  2089. }
  2090. while (pos2 != 0xF0000000);
  2091. // RcTree_ReverseEncode(&p->rc, p->posAlignEncoder, kNumAlignBits, posReduced & kAlignMask);
  2092. {
  2093. unsigned m = 1;
  2094. unsigned bit;
  2095. bit = dist & 1; dist >>= 1; RC_BIT(&p->rc, p->posAlignEncoder + m, bit); m = (m << 1) + bit;
  2096. bit = dist & 1; dist >>= 1; RC_BIT(&p->rc, p->posAlignEncoder + m, bit); m = (m << 1) + bit;
  2097. bit = dist & 1; dist >>= 1; RC_BIT(&p->rc, p->posAlignEncoder + m, bit); m = (m << 1) + bit;
  2098. bit = dist & 1; RC_BIT(&p->rc, p->posAlignEncoder + m, bit);
  2099. p->rc.range = range;
  2100. // p->alignPriceCount++;
  2101. }
  2102. }
  2103. }
  2104. }
  2105. }
  2106. nowPos32 += (UInt32)len;
  2107. p->additionalOffset -= len;
  2108. if (p->additionalOffset == 0)
  2109. {
  2110. UInt32 processed;
  2111. if (!p->fastMode)
  2112. {
  2113. /*
  2114. if (p->alignPriceCount >= 16) // kAlignTableSize
  2115. FillAlignPrices(p);
  2116. if (p->matchPriceCount >= 128)
  2117. FillDistancesPrices(p);
  2118. if (p->lenEnc.counter <= 0)
  2119. LenPriceEnc_UpdateTables(&p->lenEnc, 1 << p->pb, &p->lenProbs, p->ProbPrices);
  2120. */
  2121. if (p->matchPriceCount >= 64)
  2122. {
  2123. FillAlignPrices(p);
  2124. // { int y; for (y = 0; y < 100; y++) {
  2125. FillDistancesPrices(p);
  2126. // }}
  2127. LenPriceEnc_UpdateTables(&p->lenEnc, 1 << p->pb, &p->lenProbs, p->ProbPrices);
  2128. }
  2129. if (p->repLenEncCounter <= 0)
  2130. {
  2131. p->repLenEncCounter = REP_LEN_COUNT;
  2132. LenPriceEnc_UpdateTables(&p->repLenEnc, 1 << p->pb, &p->repLenProbs, p->ProbPrices);
  2133. }
  2134. }
  2135. if (p->matchFinder.GetNumAvailableBytes(p->matchFinderObj) == 0)
  2136. break;
  2137. processed = nowPos32 - startPos32;
  2138. if (maxPackSize)
  2139. {
  2140. if (processed + kNumOpts + 300 >= maxUnpackSize
  2141. || RangeEnc_GetProcessed_sizet(&p->rc) + kPackReserve >= maxPackSize)
  2142. break;
  2143. }
  2144. else if (processed >= (1 << 17))
  2145. {
  2146. p->nowPos64 += nowPos32 - startPos32;
  2147. return CheckErrors(p);
  2148. }
  2149. }
  2150. }
  2151. p->nowPos64 += nowPos32 - startPos32;
  2152. return Flush(p, nowPos32);
  2153. }
  2154. #define kBigHashDicLimit ((UInt32)1 << 24)
  2155. static SRes LzmaEnc_Alloc(CLzmaEnc *p, UInt32 keepWindowSize, ISzAllocPtr alloc, ISzAllocPtr allocBig)
  2156. {
  2157. UInt32 beforeSize = kNumOpts;
  2158. if (!RangeEnc_Alloc(&p->rc, alloc))
  2159. return SZ_ERROR_MEM;
  2160. #ifndef _7ZIP_ST
  2161. p->mtMode = (p->multiThread && !p->fastMode && (p->matchFinderBase.btMode != 0));
  2162. #endif
  2163. {
  2164. unsigned lclp = p->lc + p->lp;
  2165. if (!p->litProbs || !p->saveState.litProbs || p->lclp != lclp)
  2166. {
  2167. LzmaEnc_FreeLits(p, alloc);
  2168. p->litProbs = (CLzmaProb *)ISzAlloc_Alloc(alloc, ((UInt32)0x300 << lclp) * sizeof(CLzmaProb));
  2169. p->saveState.litProbs = (CLzmaProb *)ISzAlloc_Alloc(alloc, ((UInt32)0x300 << lclp) * sizeof(CLzmaProb));
  2170. if (!p->litProbs || !p->saveState.litProbs)
  2171. {
  2172. LzmaEnc_FreeLits(p, alloc);
  2173. return SZ_ERROR_MEM;
  2174. }
  2175. p->lclp = lclp;
  2176. }
  2177. }
  2178. p->matchFinderBase.bigHash = (Byte)(p->dictSize > kBigHashDicLimit ? 1 : 0);
  2179. if (beforeSize + p->dictSize < keepWindowSize)
  2180. beforeSize = keepWindowSize - p->dictSize;
  2181. #ifndef _7ZIP_ST
  2182. if (p->mtMode)
  2183. {
  2184. RINOK(MatchFinderMt_Create(&p->matchFinderMt, p->dictSize, beforeSize, p->numFastBytes,
  2185. LZMA_MATCH_LEN_MAX
  2186. + 1 /* 18.04 */
  2187. , allocBig));
  2188. p->matchFinderObj = &p->matchFinderMt;
  2189. p->matchFinderBase.bigHash = (Byte)(
  2190. (p->dictSize > kBigHashDicLimit && p->matchFinderBase.hashMask >= 0xFFFFFF) ? 1 : 0);
  2191. MatchFinderMt_CreateVTable(&p->matchFinderMt, &p->matchFinder);
  2192. }
  2193. else
  2194. #endif
  2195. {
  2196. if (!MatchFinder_Create(&p->matchFinderBase, p->dictSize, beforeSize, p->numFastBytes, LZMA_MATCH_LEN_MAX, allocBig))
  2197. return SZ_ERROR_MEM;
  2198. p->matchFinderObj = &p->matchFinderBase;
  2199. MatchFinder_CreateVTable(&p->matchFinderBase, &p->matchFinder);
  2200. }
  2201. return SZ_OK;
  2202. }
  2203. void LzmaEnc_Init(CLzmaEnc *p)
  2204. {
  2205. unsigned i;
  2206. p->state = 0;
  2207. p->reps[0] =
  2208. p->reps[1] =
  2209. p->reps[2] =
  2210. p->reps[3] = 1;
  2211. RangeEnc_Init(&p->rc);
  2212. for (i = 0; i < (1 << kNumAlignBits); i++)
  2213. p->posAlignEncoder[i] = kProbInitValue;
  2214. for (i = 0; i < kNumStates; i++)
  2215. {
  2216. unsigned j;
  2217. for (j = 0; j < LZMA_NUM_PB_STATES_MAX; j++)
  2218. {
  2219. p->isMatch[i][j] = kProbInitValue;
  2220. p->isRep0Long[i][j] = kProbInitValue;
  2221. }
  2222. p->isRep[i] = kProbInitValue;
  2223. p->isRepG0[i] = kProbInitValue;
  2224. p->isRepG1[i] = kProbInitValue;
  2225. p->isRepG2[i] = kProbInitValue;
  2226. }
  2227. {
  2228. for (i = 0; i < kNumLenToPosStates; i++)
  2229. {
  2230. CLzmaProb *probs = p->posSlotEncoder[i];
  2231. unsigned j;
  2232. for (j = 0; j < (1 << kNumPosSlotBits); j++)
  2233. probs[j] = kProbInitValue;
  2234. }
  2235. }
  2236. {
  2237. for (i = 0; i < kNumFullDistances; i++)
  2238. p->posEncoders[i] = kProbInitValue;
  2239. }
  2240. {
  2241. UInt32 num = (UInt32)0x300 << (p->lp + p->lc);
  2242. UInt32 k;
  2243. CLzmaProb *probs = p->litProbs;
  2244. for (k = 0; k < num; k++)
  2245. probs[k] = kProbInitValue;
  2246. }
  2247. LenEnc_Init(&p->lenProbs);
  2248. LenEnc_Init(&p->repLenProbs);
  2249. p->optEnd = 0;
  2250. p->optCur = 0;
  2251. {
  2252. for (i = 0; i < kNumOpts; i++)
  2253. p->opt[i].price = kInfinityPrice;
  2254. }
  2255. p->additionalOffset = 0;
  2256. p->pbMask = (1 << p->pb) - 1;
  2257. p->lpMask = ((UInt32)0x100 << p->lp) - ((unsigned)0x100 >> p->lc);
  2258. }
  2259. void LzmaEnc_InitPrices(CLzmaEnc *p)
  2260. {
  2261. if (!p->fastMode)
  2262. {
  2263. FillDistancesPrices(p);
  2264. FillAlignPrices(p);
  2265. }
  2266. p->lenEnc.tableSize =
  2267. p->repLenEnc.tableSize =
  2268. p->numFastBytes + 1 - LZMA_MATCH_LEN_MIN;
  2269. p->repLenEncCounter = REP_LEN_COUNT;
  2270. LenPriceEnc_UpdateTables(&p->lenEnc, 1 << p->pb, &p->lenProbs, p->ProbPrices);
  2271. LenPriceEnc_UpdateTables(&p->repLenEnc, 1 << p->pb, &p->repLenProbs, p->ProbPrices);
  2272. }
  2273. static SRes LzmaEnc_AllocAndInit(CLzmaEnc *p, UInt32 keepWindowSize, ISzAllocPtr alloc, ISzAllocPtr allocBig)
  2274. {
  2275. unsigned i;
  2276. for (i = kEndPosModelIndex / 2; i < kDicLogSizeMax; i++)
  2277. if (p->dictSize <= ((UInt32)1 << i))
  2278. break;
  2279. p->distTableSize = i * 2;
  2280. p->finished = False;
  2281. p->result = SZ_OK;
  2282. RINOK(LzmaEnc_Alloc(p, keepWindowSize, alloc, allocBig));
  2283. LzmaEnc_Init(p);
  2284. LzmaEnc_InitPrices(p);
  2285. p->nowPos64 = 0;
  2286. return SZ_OK;
  2287. }
  2288. SRes LzmaEnc_Prepare(CLzmaEncHandle pp, ISeqOutStream *outStream, ISeqInStream *inStream,
  2289. ISzAllocPtr alloc, ISzAllocPtr allocBig)
  2290. {
  2291. CLzmaEnc *p = (CLzmaEnc *)pp;
  2292. p->matchFinderBase.stream = inStream;
  2293. p->needInit = 1;
  2294. p->rc.outStream = outStream;
  2295. return LzmaEnc_AllocAndInit(p, 0, alloc, allocBig);
  2296. }
  2297. SRes LzmaEnc_PrepareForLzma2(CLzmaEncHandle pp,
  2298. ISeqInStream *inStream, UInt32 keepWindowSize,
  2299. ISzAllocPtr alloc, ISzAllocPtr allocBig)
  2300. {
  2301. CLzmaEnc *p = (CLzmaEnc *)pp;
  2302. p->matchFinderBase.stream = inStream;
  2303. p->needInit = 1;
  2304. return LzmaEnc_AllocAndInit(p, keepWindowSize, alloc, allocBig);
  2305. }
  2306. static void LzmaEnc_SetInputBuf(CLzmaEnc *p, const Byte *src, SizeT srcLen)
  2307. {
  2308. p->matchFinderBase.directInput = 1;
  2309. p->matchFinderBase.bufferBase = (Byte *)src;
  2310. p->matchFinderBase.directInputRem = srcLen;
  2311. }
  2312. SRes LzmaEnc_MemPrepare(CLzmaEncHandle pp, const Byte *src, SizeT srcLen,
  2313. UInt32 keepWindowSize, ISzAllocPtr alloc, ISzAllocPtr allocBig)
  2314. {
  2315. CLzmaEnc *p = (CLzmaEnc *)pp;
  2316. LzmaEnc_SetInputBuf(p, src, srcLen);
  2317. p->needInit = 1;
  2318. LzmaEnc_SetDataSize(pp, srcLen);
  2319. return LzmaEnc_AllocAndInit(p, keepWindowSize, alloc, allocBig);
  2320. }
  2321. void LzmaEnc_Finish(CLzmaEncHandle pp)
  2322. {
  2323. #ifndef _7ZIP_ST
  2324. CLzmaEnc *p = (CLzmaEnc *)pp;
  2325. if (p->mtMode)
  2326. MatchFinderMt_ReleaseStream(&p->matchFinderMt);
  2327. #else
  2328. UNUSED_VAR(pp);
  2329. #endif
  2330. }
  2331. typedef struct
  2332. {
  2333. ISeqOutStream vt;
  2334. Byte *data;
  2335. SizeT rem;
  2336. BoolInt overflow;
  2337. } CLzmaEnc_SeqOutStreamBuf;
  2338. static size_t SeqOutStreamBuf_Write(const ISeqOutStream *pp, const void *data, size_t size)
  2339. {
  2340. CLzmaEnc_SeqOutStreamBuf *p = CONTAINER_FROM_VTBL(pp, CLzmaEnc_SeqOutStreamBuf, vt);
  2341. if (p->rem < size)
  2342. {
  2343. size = p->rem;
  2344. p->overflow = True;
  2345. }
  2346. memcpy(p->data, data, size);
  2347. p->rem -= size;
  2348. p->data += size;
  2349. return size;
  2350. }
  2351. UInt32 LzmaEnc_GetNumAvailableBytes(CLzmaEncHandle pp)
  2352. {
  2353. const CLzmaEnc *p = (CLzmaEnc *)pp;
  2354. return p->matchFinder.GetNumAvailableBytes(p->matchFinderObj);
  2355. }
  2356. const Byte *LzmaEnc_GetCurBuf(CLzmaEncHandle pp)
  2357. {
  2358. const CLzmaEnc *p = (CLzmaEnc *)pp;
  2359. return p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - p->additionalOffset;
  2360. }
  2361. SRes LzmaEnc_CodeOneMemBlock(CLzmaEncHandle pp, BoolInt reInit,
  2362. Byte *dest, size_t *destLen, UInt32 desiredPackSize, UInt32 *unpackSize)
  2363. {
  2364. CLzmaEnc *p = (CLzmaEnc *)pp;
  2365. UInt64 nowPos64;
  2366. SRes res;
  2367. CLzmaEnc_SeqOutStreamBuf outStream;
  2368. outStream.vt.Write = SeqOutStreamBuf_Write;
  2369. outStream.data = dest;
  2370. outStream.rem = *destLen;
  2371. outStream.overflow = False;
  2372. p->writeEndMark = False;
  2373. p->finished = False;
  2374. p->result = SZ_OK;
  2375. if (reInit)
  2376. LzmaEnc_Init(p);
  2377. LzmaEnc_InitPrices(p);
  2378. nowPos64 = p->nowPos64;
  2379. RangeEnc_Init(&p->rc);
  2380. p->rc.outStream = &outStream.vt;
  2381. if (desiredPackSize == 0)
  2382. return SZ_ERROR_OUTPUT_EOF;
  2383. res = LzmaEnc_CodeOneBlock(p, desiredPackSize, *unpackSize);
  2384. *unpackSize = (UInt32)(p->nowPos64 - nowPos64);
  2385. *destLen -= outStream.rem;
  2386. if (outStream.overflow)
  2387. return SZ_ERROR_OUTPUT_EOF;
  2388. return res;
  2389. }
  2390. static SRes LzmaEnc_Encode2(CLzmaEnc *p, ICompressProgress *progress)
  2391. {
  2392. SRes res = SZ_OK;
  2393. #ifndef _7ZIP_ST
  2394. Byte allocaDummy[0x300];
  2395. allocaDummy[0] = 0;
  2396. allocaDummy[1] = allocaDummy[0];
  2397. #endif
  2398. for (;;)
  2399. {
  2400. res = LzmaEnc_CodeOneBlock(p, 0, 0);
  2401. if (res != SZ_OK || p->finished)
  2402. break;
  2403. if (progress)
  2404. {
  2405. res = ICompressProgress_Progress(progress, p->nowPos64, RangeEnc_GetProcessed(&p->rc));
  2406. if (res != SZ_OK)
  2407. {
  2408. res = SZ_ERROR_PROGRESS;
  2409. break;
  2410. }
  2411. }
  2412. }
  2413. LzmaEnc_Finish(p);
  2414. /*
  2415. if (res == SZ_OK && !Inline_MatchFinder_IsFinishedOK(&p->matchFinderBase))
  2416. res = SZ_ERROR_FAIL;
  2417. }
  2418. */
  2419. return res;
  2420. }
  2421. SRes LzmaEnc_Encode(CLzmaEncHandle pp, ISeqOutStream *outStream, ISeqInStream *inStream, ICompressProgress *progress,
  2422. ISzAllocPtr alloc, ISzAllocPtr allocBig)
  2423. {
  2424. RINOK(LzmaEnc_Prepare(pp, outStream, inStream, alloc, allocBig));
  2425. return LzmaEnc_Encode2((CLzmaEnc *)pp, progress);
  2426. }
  2427. SRes LzmaEnc_WriteProperties(CLzmaEncHandle pp, Byte *props, SizeT *size)
  2428. {
  2429. CLzmaEnc *p = (CLzmaEnc *)pp;
  2430. unsigned i;
  2431. UInt32 dictSize = p->dictSize;
  2432. if (*size < LZMA_PROPS_SIZE)
  2433. return SZ_ERROR_PARAM;
  2434. *size = LZMA_PROPS_SIZE;
  2435. props[0] = (Byte)((p->pb * 5 + p->lp) * 9 + p->lc);
  2436. if (dictSize >= ((UInt32)1 << 22))
  2437. {
  2438. UInt32 kDictMask = ((UInt32)1 << 20) - 1;
  2439. if (dictSize < (UInt32)0xFFFFFFFF - kDictMask)
  2440. dictSize = (dictSize + kDictMask) & ~kDictMask;
  2441. }
  2442. else for (i = 11; i <= 30; i++)
  2443. {
  2444. if (dictSize <= ((UInt32)2 << i)) { dictSize = (2 << i); break; }
  2445. if (dictSize <= ((UInt32)3 << i)) { dictSize = (3 << i); break; }
  2446. }
  2447. for (i = 0; i < 4; i++)
  2448. props[1 + i] = (Byte)(dictSize >> (8 * i));
  2449. return SZ_OK;
  2450. }
  2451. unsigned LzmaEnc_IsWriteEndMark(CLzmaEncHandle pp)
  2452. {
  2453. return ((CLzmaEnc *)pp)->writeEndMark;
  2454. }
  2455. SRes LzmaEnc_MemEncode(CLzmaEncHandle pp, Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen,
  2456. int writeEndMark, ICompressProgress *progress, ISzAllocPtr alloc, ISzAllocPtr allocBig)
  2457. {
  2458. SRes res;
  2459. CLzmaEnc *p = (CLzmaEnc *)pp;
  2460. CLzmaEnc_SeqOutStreamBuf outStream;
  2461. outStream.vt.Write = SeqOutStreamBuf_Write;
  2462. outStream.data = dest;
  2463. outStream.rem = *destLen;
  2464. outStream.overflow = False;
  2465. p->writeEndMark = writeEndMark;
  2466. p->rc.outStream = &outStream.vt;
  2467. res = LzmaEnc_MemPrepare(pp, src, srcLen, 0, alloc, allocBig);
  2468. if (res == SZ_OK)
  2469. {
  2470. res = LzmaEnc_Encode2(p, progress);
  2471. if (res == SZ_OK && p->nowPos64 != srcLen)
  2472. res = SZ_ERROR_FAIL;
  2473. }
  2474. *destLen -= outStream.rem;
  2475. if (outStream.overflow)
  2476. return SZ_ERROR_OUTPUT_EOF;
  2477. return res;
  2478. }
  2479. SRes LzmaEncode(Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen,
  2480. const CLzmaEncProps *props, Byte *propsEncoded, SizeT *propsSize, int writeEndMark,
  2481. ICompressProgress *progress, ISzAllocPtr alloc, ISzAllocPtr allocBig)
  2482. {
  2483. CLzmaEnc *p = (CLzmaEnc *)LzmaEnc_Create(alloc);
  2484. SRes res;
  2485. if (!p)
  2486. return SZ_ERROR_MEM;
  2487. res = LzmaEnc_SetProps(p, props);
  2488. if (res == SZ_OK)
  2489. {
  2490. res = LzmaEnc_WriteProperties(p, propsEncoded, propsSize);
  2491. if (res == SZ_OK)
  2492. res = LzmaEnc_MemEncode(p, dest, destLen, src, srcLen,
  2493. writeEndMark, progress, alloc, allocBig);
  2494. }
  2495. LzmaEnc_Destroy(p, alloc, allocBig);
  2496. return res;
  2497. }
  2498. BoolInt LzmaEnc_IsFinished(CLzmaEncHandle pp)
  2499. {
  2500. CLzmaEnc *p = (CLzmaEnc *)pp;
  2501. return p->finished;
  2502. }