LzmaEnc.c 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976
  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. static SRes LzmaEnc_CodeOneBlock(CLzmaEnc *p, UInt32 maxPackSize, UInt32 maxUnpackSize)
  1892. {
  1893. UInt32 nowPos32, startPos32;
  1894. if (p->needInit)
  1895. {
  1896. p->matchFinder.Init(p->matchFinderObj);
  1897. p->needInit = 0;
  1898. }
  1899. if (p->finished)
  1900. return p->result;
  1901. RINOK(CheckErrors(p));
  1902. nowPos32 = (UInt32)p->nowPos64;
  1903. startPos32 = nowPos32;
  1904. if (p->nowPos64 == 0)
  1905. {
  1906. unsigned numPairs;
  1907. Byte curByte;
  1908. if (p->matchFinder.GetNumAvailableBytes(p->matchFinderObj) == 0)
  1909. return Flush(p, nowPos32);
  1910. ReadMatchDistances(p, &numPairs);
  1911. RangeEnc_EncodeBit_0(&p->rc, &p->isMatch[kState_Start][0]);
  1912. // p->state = kLiteralNextStates[p->state];
  1913. curByte = *(p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - p->additionalOffset);
  1914. LitEnc_Encode(&p->rc, p->litProbs, curByte);
  1915. p->additionalOffset--;
  1916. nowPos32++;
  1917. }
  1918. if (p->matchFinder.GetNumAvailableBytes(p->matchFinderObj) != 0)
  1919. for (;;)
  1920. {
  1921. UInt32 dist;
  1922. unsigned len, posState;
  1923. UInt32 range, ttt, newBound;
  1924. CLzmaProb *probs;
  1925. if (p->fastMode)
  1926. len = GetOptimumFast(p);
  1927. else
  1928. {
  1929. unsigned oci = p->optCur;
  1930. if (p->optEnd == oci)
  1931. len = GetOptimum(p, nowPos32);
  1932. else
  1933. {
  1934. const COptimal *opt = &p->opt[oci];
  1935. len = opt->len;
  1936. p->backRes = opt->dist;
  1937. p->optCur = oci + 1;
  1938. }
  1939. }
  1940. posState = (unsigned)nowPos32 & p->pbMask;
  1941. range = p->rc.range;
  1942. probs = &p->isMatch[p->state][posState];
  1943. RC_BIT_PRE(&p->rc, probs)
  1944. dist = p->backRes;
  1945. #ifdef SHOW_STAT2
  1946. printf("\n pos = %6X, len = %3u pos = %6u", nowPos32, len, dist);
  1947. #endif
  1948. if (dist == MARK_LIT)
  1949. {
  1950. Byte curByte;
  1951. const Byte *data;
  1952. unsigned state;
  1953. RC_BIT_0(&p->rc, probs);
  1954. p->rc.range = range;
  1955. data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - p->additionalOffset;
  1956. probs = LIT_PROBS(nowPos32, *(data - 1));
  1957. curByte = *data;
  1958. state = p->state;
  1959. p->state = kLiteralNextStates[state];
  1960. if (IsLitState(state))
  1961. LitEnc_Encode(&p->rc, probs, curByte);
  1962. else
  1963. LitEnc_EncodeMatched(&p->rc, probs, curByte, *(data - p->reps[0]));
  1964. }
  1965. else
  1966. {
  1967. RC_BIT_1(&p->rc, probs);
  1968. probs = &p->isRep[p->state];
  1969. RC_BIT_PRE(&p->rc, probs)
  1970. if (dist < LZMA_NUM_REPS)
  1971. {
  1972. RC_BIT_1(&p->rc, probs);
  1973. probs = &p->isRepG0[p->state];
  1974. RC_BIT_PRE(&p->rc, probs)
  1975. if (dist == 0)
  1976. {
  1977. RC_BIT_0(&p->rc, probs);
  1978. probs = &p->isRep0Long[p->state][posState];
  1979. RC_BIT_PRE(&p->rc, probs)
  1980. if (len != 1)
  1981. {
  1982. RC_BIT_1_BASE(&p->rc, probs);
  1983. }
  1984. else
  1985. {
  1986. RC_BIT_0_BASE(&p->rc, probs);
  1987. p->state = kShortRepNextStates[p->state];
  1988. }
  1989. }
  1990. else
  1991. {
  1992. RC_BIT_1(&p->rc, probs);
  1993. probs = &p->isRepG1[p->state];
  1994. RC_BIT_PRE(&p->rc, probs)
  1995. if (dist == 1)
  1996. {
  1997. RC_BIT_0_BASE(&p->rc, probs);
  1998. dist = p->reps[1];
  1999. }
  2000. else
  2001. {
  2002. RC_BIT_1(&p->rc, probs);
  2003. probs = &p->isRepG2[p->state];
  2004. RC_BIT_PRE(&p->rc, probs)
  2005. if (dist == 2)
  2006. {
  2007. RC_BIT_0_BASE(&p->rc, probs);
  2008. dist = p->reps[2];
  2009. }
  2010. else
  2011. {
  2012. RC_BIT_1_BASE(&p->rc, probs);
  2013. dist = p->reps[3];
  2014. p->reps[3] = p->reps[2];
  2015. }
  2016. p->reps[2] = p->reps[1];
  2017. }
  2018. p->reps[1] = p->reps[0];
  2019. p->reps[0] = dist;
  2020. }
  2021. RC_NORM(&p->rc)
  2022. p->rc.range = range;
  2023. if (len != 1)
  2024. {
  2025. LenEnc_Encode(&p->repLenProbs, &p->rc, len - LZMA_MATCH_LEN_MIN, posState);
  2026. --p->repLenEncCounter;
  2027. p->state = kRepNextStates[p->state];
  2028. }
  2029. }
  2030. else
  2031. {
  2032. unsigned posSlot;
  2033. RC_BIT_0(&p->rc, probs);
  2034. p->rc.range = range;
  2035. p->state = kMatchNextStates[p->state];
  2036. LenEnc_Encode(&p->lenProbs, &p->rc, len - LZMA_MATCH_LEN_MIN, posState);
  2037. // --p->lenEnc.counter;
  2038. dist -= LZMA_NUM_REPS;
  2039. p->reps[3] = p->reps[2];
  2040. p->reps[2] = p->reps[1];
  2041. p->reps[1] = p->reps[0];
  2042. p->reps[0] = dist + 1;
  2043. p->matchPriceCount++;
  2044. GetPosSlot(dist, posSlot);
  2045. // RcTree_Encode_PosSlot(&p->rc, p->posSlotEncoder[GetLenToPosState(len)], posSlot);
  2046. {
  2047. UInt32 sym = (UInt32)posSlot + (1 << kNumPosSlotBits);
  2048. range = p->rc.range;
  2049. probs = p->posSlotEncoder[GetLenToPosState(len)];
  2050. do
  2051. {
  2052. CLzmaProb *prob = probs + (sym >> kNumPosSlotBits);
  2053. UInt32 bit = (sym >> (kNumPosSlotBits - 1)) & 1;
  2054. sym <<= 1;
  2055. RC_BIT(&p->rc, prob, bit);
  2056. }
  2057. while (sym < (1 << kNumPosSlotBits * 2));
  2058. p->rc.range = range;
  2059. }
  2060. if (dist >= kStartPosModelIndex)
  2061. {
  2062. unsigned footerBits = ((posSlot >> 1) - 1);
  2063. if (dist < kNumFullDistances)
  2064. {
  2065. unsigned base = ((2 | (posSlot & 1)) << footerBits);
  2066. RcTree_ReverseEncode(&p->rc, p->posEncoders + base, footerBits, (unsigned)(dist /* - base */));
  2067. }
  2068. else
  2069. {
  2070. UInt32 pos2 = (dist | 0xF) << (32 - footerBits);
  2071. range = p->rc.range;
  2072. // RangeEnc_EncodeDirectBits(&p->rc, posReduced >> kNumAlignBits, footerBits - kNumAlignBits);
  2073. /*
  2074. do
  2075. {
  2076. range >>= 1;
  2077. p->rc.low += range & (0 - ((dist >> --footerBits) & 1));
  2078. RC_NORM(&p->rc)
  2079. }
  2080. while (footerBits > kNumAlignBits);
  2081. */
  2082. do
  2083. {
  2084. range >>= 1;
  2085. p->rc.low += range & (0 - (pos2 >> 31));
  2086. pos2 += pos2;
  2087. RC_NORM(&p->rc)
  2088. }
  2089. while (pos2 != 0xF0000000);
  2090. // RcTree_ReverseEncode(&p->rc, p->posAlignEncoder, kNumAlignBits, posReduced & kAlignMask);
  2091. {
  2092. unsigned m = 1;
  2093. unsigned bit;
  2094. bit = dist & 1; dist >>= 1; RC_BIT(&p->rc, p->posAlignEncoder + m, bit); m = (m << 1) + 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; RC_BIT(&p->rc, p->posAlignEncoder + m, bit);
  2098. p->rc.range = range;
  2099. // p->alignPriceCount++;
  2100. }
  2101. }
  2102. }
  2103. }
  2104. }
  2105. nowPos32 += (UInt32)len;
  2106. p->additionalOffset -= len;
  2107. if (p->additionalOffset == 0)
  2108. {
  2109. UInt32 processed;
  2110. if (!p->fastMode)
  2111. {
  2112. /*
  2113. if (p->alignPriceCount >= 16) // kAlignTableSize
  2114. FillAlignPrices(p);
  2115. if (p->matchPriceCount >= 128)
  2116. FillDistancesPrices(p);
  2117. if (p->lenEnc.counter <= 0)
  2118. LenPriceEnc_UpdateTables(&p->lenEnc, 1 << p->pb, &p->lenProbs, p->ProbPrices);
  2119. */
  2120. if (p->matchPriceCount >= 64)
  2121. {
  2122. FillAlignPrices(p);
  2123. // { int y; for (y = 0; y < 100; y++) {
  2124. FillDistancesPrices(p);
  2125. // }}
  2126. LenPriceEnc_UpdateTables(&p->lenEnc, 1 << p->pb, &p->lenProbs, p->ProbPrices);
  2127. }
  2128. if (p->repLenEncCounter <= 0)
  2129. {
  2130. p->repLenEncCounter = REP_LEN_COUNT;
  2131. LenPriceEnc_UpdateTables(&p->repLenEnc, 1 << p->pb, &p->repLenProbs, p->ProbPrices);
  2132. }
  2133. }
  2134. if (p->matchFinder.GetNumAvailableBytes(p->matchFinderObj) == 0)
  2135. break;
  2136. processed = nowPos32 - startPos32;
  2137. if (maxPackSize)
  2138. {
  2139. if (processed + kNumOpts + 300 >= maxUnpackSize
  2140. || RangeEnc_GetProcessed_sizet(&p->rc) + kPackReserve >= maxPackSize)
  2141. break;
  2142. }
  2143. else if (processed >= (1 << 17))
  2144. {
  2145. p->nowPos64 += nowPos32 - startPos32;
  2146. return CheckErrors(p);
  2147. }
  2148. }
  2149. }
  2150. p->nowPos64 += nowPos32 - startPos32;
  2151. return Flush(p, nowPos32);
  2152. }
  2153. #define kBigHashDicLimit ((UInt32)1 << 24)
  2154. static SRes LzmaEnc_Alloc(CLzmaEnc *p, UInt32 keepWindowSize, ISzAllocPtr alloc, ISzAllocPtr allocBig)
  2155. {
  2156. UInt32 beforeSize = kNumOpts;
  2157. if (!RangeEnc_Alloc(&p->rc, alloc))
  2158. return SZ_ERROR_MEM;
  2159. #ifndef _7ZIP_ST
  2160. p->mtMode = (p->multiThread && !p->fastMode && (p->matchFinderBase.btMode != 0));
  2161. #endif
  2162. {
  2163. unsigned lclp = p->lc + p->lp;
  2164. if (!p->litProbs || !p->saveState.litProbs || p->lclp != lclp)
  2165. {
  2166. LzmaEnc_FreeLits(p, alloc);
  2167. p->litProbs = (CLzmaProb *)ISzAlloc_Alloc(alloc, ((UInt32)0x300 << lclp) * sizeof(CLzmaProb));
  2168. p->saveState.litProbs = (CLzmaProb *)ISzAlloc_Alloc(alloc, ((UInt32)0x300 << lclp) * sizeof(CLzmaProb));
  2169. if (!p->litProbs || !p->saveState.litProbs)
  2170. {
  2171. LzmaEnc_FreeLits(p, alloc);
  2172. return SZ_ERROR_MEM;
  2173. }
  2174. p->lclp = lclp;
  2175. }
  2176. }
  2177. p->matchFinderBase.bigHash = (Byte)(p->dictSize > kBigHashDicLimit ? 1 : 0);
  2178. if (beforeSize + p->dictSize < keepWindowSize)
  2179. beforeSize = keepWindowSize - p->dictSize;
  2180. #ifndef _7ZIP_ST
  2181. if (p->mtMode)
  2182. {
  2183. RINOK(MatchFinderMt_Create(&p->matchFinderMt, p->dictSize, beforeSize, p->numFastBytes,
  2184. LZMA_MATCH_LEN_MAX
  2185. + 1 /* 18.04 */
  2186. , allocBig));
  2187. p->matchFinderObj = &p->matchFinderMt;
  2188. p->matchFinderBase.bigHash = (Byte)(
  2189. (p->dictSize > kBigHashDicLimit && p->matchFinderBase.hashMask >= 0xFFFFFF) ? 1 : 0);
  2190. MatchFinderMt_CreateVTable(&p->matchFinderMt, &p->matchFinder);
  2191. }
  2192. else
  2193. #endif
  2194. {
  2195. if (!MatchFinder_Create(&p->matchFinderBase, p->dictSize, beforeSize, p->numFastBytes, LZMA_MATCH_LEN_MAX, allocBig))
  2196. return SZ_ERROR_MEM;
  2197. p->matchFinderObj = &p->matchFinderBase;
  2198. MatchFinder_CreateVTable(&p->matchFinderBase, &p->matchFinder);
  2199. }
  2200. return SZ_OK;
  2201. }
  2202. void LzmaEnc_Init(CLzmaEnc *p)
  2203. {
  2204. unsigned i;
  2205. p->state = 0;
  2206. p->reps[0] =
  2207. p->reps[1] =
  2208. p->reps[2] =
  2209. p->reps[3] = 1;
  2210. RangeEnc_Init(&p->rc);
  2211. for (i = 0; i < (1 << kNumAlignBits); i++)
  2212. p->posAlignEncoder[i] = kProbInitValue;
  2213. for (i = 0; i < kNumStates; i++)
  2214. {
  2215. unsigned j;
  2216. for (j = 0; j < LZMA_NUM_PB_STATES_MAX; j++)
  2217. {
  2218. p->isMatch[i][j] = kProbInitValue;
  2219. p->isRep0Long[i][j] = kProbInitValue;
  2220. }
  2221. p->isRep[i] = kProbInitValue;
  2222. p->isRepG0[i] = kProbInitValue;
  2223. p->isRepG1[i] = kProbInitValue;
  2224. p->isRepG2[i] = kProbInitValue;
  2225. }
  2226. {
  2227. for (i = 0; i < kNumLenToPosStates; i++)
  2228. {
  2229. CLzmaProb *probs = p->posSlotEncoder[i];
  2230. unsigned j;
  2231. for (j = 0; j < (1 << kNumPosSlotBits); j++)
  2232. probs[j] = kProbInitValue;
  2233. }
  2234. }
  2235. {
  2236. for (i = 0; i < kNumFullDistances; i++)
  2237. p->posEncoders[i] = kProbInitValue;
  2238. }
  2239. {
  2240. UInt32 num = (UInt32)0x300 << (p->lp + p->lc);
  2241. UInt32 k;
  2242. CLzmaProb *probs = p->litProbs;
  2243. for (k = 0; k < num; k++)
  2244. probs[k] = kProbInitValue;
  2245. }
  2246. LenEnc_Init(&p->lenProbs);
  2247. LenEnc_Init(&p->repLenProbs);
  2248. p->optEnd = 0;
  2249. p->optCur = 0;
  2250. {
  2251. for (i = 0; i < kNumOpts; i++)
  2252. p->opt[i].price = kInfinityPrice;
  2253. }
  2254. p->additionalOffset = 0;
  2255. p->pbMask = (1 << p->pb) - 1;
  2256. p->lpMask = ((UInt32)0x100 << p->lp) - ((unsigned)0x100 >> p->lc);
  2257. }
  2258. void LzmaEnc_InitPrices(CLzmaEnc *p)
  2259. {
  2260. if (!p->fastMode)
  2261. {
  2262. FillDistancesPrices(p);
  2263. FillAlignPrices(p);
  2264. }
  2265. p->lenEnc.tableSize =
  2266. p->repLenEnc.tableSize =
  2267. p->numFastBytes + 1 - LZMA_MATCH_LEN_MIN;
  2268. p->repLenEncCounter = REP_LEN_COUNT;
  2269. LenPriceEnc_UpdateTables(&p->lenEnc, 1 << p->pb, &p->lenProbs, p->ProbPrices);
  2270. LenPriceEnc_UpdateTables(&p->repLenEnc, 1 << p->pb, &p->repLenProbs, p->ProbPrices);
  2271. }
  2272. static SRes LzmaEnc_AllocAndInit(CLzmaEnc *p, UInt32 keepWindowSize, ISzAllocPtr alloc, ISzAllocPtr allocBig)
  2273. {
  2274. unsigned i;
  2275. for (i = kEndPosModelIndex / 2; i < kDicLogSizeMax; i++)
  2276. if (p->dictSize <= ((UInt32)1 << i))
  2277. break;
  2278. p->distTableSize = i * 2;
  2279. p->finished = False;
  2280. p->result = SZ_OK;
  2281. RINOK(LzmaEnc_Alloc(p, keepWindowSize, alloc, allocBig));
  2282. LzmaEnc_Init(p);
  2283. LzmaEnc_InitPrices(p);
  2284. p->nowPos64 = 0;
  2285. return SZ_OK;
  2286. }
  2287. static SRes LzmaEnc_Prepare(CLzmaEncHandle pp, ISeqOutStream *outStream, ISeqInStream *inStream,
  2288. ISzAllocPtr alloc, ISzAllocPtr allocBig)
  2289. {
  2290. CLzmaEnc *p = (CLzmaEnc *)pp;
  2291. p->matchFinderBase.stream = inStream;
  2292. p->needInit = 1;
  2293. p->rc.outStream = outStream;
  2294. return LzmaEnc_AllocAndInit(p, 0, alloc, allocBig);
  2295. }
  2296. SRes LzmaEnc_PrepareForLzma2(CLzmaEncHandle pp,
  2297. ISeqInStream *inStream, UInt32 keepWindowSize,
  2298. ISzAllocPtr alloc, ISzAllocPtr allocBig)
  2299. {
  2300. CLzmaEnc *p = (CLzmaEnc *)pp;
  2301. p->matchFinderBase.stream = inStream;
  2302. p->needInit = 1;
  2303. return LzmaEnc_AllocAndInit(p, keepWindowSize, alloc, allocBig);
  2304. }
  2305. static void LzmaEnc_SetInputBuf(CLzmaEnc *p, const Byte *src, SizeT srcLen)
  2306. {
  2307. p->matchFinderBase.directInput = 1;
  2308. p->matchFinderBase.bufferBase = (Byte *)src;
  2309. p->matchFinderBase.directInputRem = srcLen;
  2310. }
  2311. SRes LzmaEnc_MemPrepare(CLzmaEncHandle pp, const Byte *src, SizeT srcLen,
  2312. UInt32 keepWindowSize, ISzAllocPtr alloc, ISzAllocPtr allocBig)
  2313. {
  2314. CLzmaEnc *p = (CLzmaEnc *)pp;
  2315. LzmaEnc_SetInputBuf(p, src, srcLen);
  2316. p->needInit = 1;
  2317. LzmaEnc_SetDataSize(pp, srcLen);
  2318. return LzmaEnc_AllocAndInit(p, keepWindowSize, alloc, allocBig);
  2319. }
  2320. void LzmaEnc_Finish(CLzmaEncHandle pp)
  2321. {
  2322. #ifndef _7ZIP_ST
  2323. CLzmaEnc *p = (CLzmaEnc *)pp;
  2324. if (p->mtMode)
  2325. MatchFinderMt_ReleaseStream(&p->matchFinderMt);
  2326. #else
  2327. UNUSED_VAR(pp);
  2328. #endif
  2329. }
  2330. typedef struct
  2331. {
  2332. ISeqOutStream vt;
  2333. Byte *data;
  2334. SizeT rem;
  2335. BoolInt overflow;
  2336. } CLzmaEnc_SeqOutStreamBuf;
  2337. static size_t SeqOutStreamBuf_Write(const ISeqOutStream *pp, const void *data, size_t size)
  2338. {
  2339. CLzmaEnc_SeqOutStreamBuf *p = CONTAINER_FROM_VTBL(pp, CLzmaEnc_SeqOutStreamBuf, vt);
  2340. if (p->rem < size)
  2341. {
  2342. size = p->rem;
  2343. p->overflow = True;
  2344. }
  2345. memcpy(p->data, data, size);
  2346. p->rem -= size;
  2347. p->data += size;
  2348. return size;
  2349. }
  2350. UInt32 LzmaEnc_GetNumAvailableBytes(CLzmaEncHandle pp)
  2351. {
  2352. const CLzmaEnc *p = (CLzmaEnc *)pp;
  2353. return p->matchFinder.GetNumAvailableBytes(p->matchFinderObj);
  2354. }
  2355. const Byte *LzmaEnc_GetCurBuf(CLzmaEncHandle pp)
  2356. {
  2357. const CLzmaEnc *p = (CLzmaEnc *)pp;
  2358. return p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - p->additionalOffset;
  2359. }
  2360. SRes LzmaEnc_CodeOneMemBlock(CLzmaEncHandle pp, BoolInt reInit,
  2361. Byte *dest, size_t *destLen, UInt32 desiredPackSize, UInt32 *unpackSize)
  2362. {
  2363. CLzmaEnc *p = (CLzmaEnc *)pp;
  2364. UInt64 nowPos64;
  2365. SRes res;
  2366. CLzmaEnc_SeqOutStreamBuf outStream;
  2367. outStream.vt.Write = SeqOutStreamBuf_Write;
  2368. outStream.data = dest;
  2369. outStream.rem = *destLen;
  2370. outStream.overflow = False;
  2371. p->writeEndMark = False;
  2372. p->finished = False;
  2373. p->result = SZ_OK;
  2374. if (reInit)
  2375. LzmaEnc_Init(p);
  2376. LzmaEnc_InitPrices(p);
  2377. nowPos64 = p->nowPos64;
  2378. RangeEnc_Init(&p->rc);
  2379. p->rc.outStream = &outStream.vt;
  2380. if (desiredPackSize == 0)
  2381. return SZ_ERROR_OUTPUT_EOF;
  2382. res = LzmaEnc_CodeOneBlock(p, desiredPackSize, *unpackSize);
  2383. *unpackSize = (UInt32)(p->nowPos64 - nowPos64);
  2384. *destLen -= outStream.rem;
  2385. if (outStream.overflow)
  2386. return SZ_ERROR_OUTPUT_EOF;
  2387. return res;
  2388. }
  2389. static SRes LzmaEnc_Encode2(CLzmaEnc *p, ICompressProgress *progress)
  2390. {
  2391. SRes res = SZ_OK;
  2392. #ifndef _7ZIP_ST
  2393. Byte allocaDummy[0x300];
  2394. allocaDummy[0] = 0;
  2395. allocaDummy[1] = allocaDummy[0];
  2396. #endif
  2397. for (;;)
  2398. {
  2399. res = LzmaEnc_CodeOneBlock(p, 0, 0);
  2400. if (res != SZ_OK || p->finished)
  2401. break;
  2402. if (progress)
  2403. {
  2404. res = ICompressProgress_Progress(progress, p->nowPos64, RangeEnc_GetProcessed(&p->rc));
  2405. if (res != SZ_OK)
  2406. {
  2407. res = SZ_ERROR_PROGRESS;
  2408. break;
  2409. }
  2410. }
  2411. }
  2412. LzmaEnc_Finish(p);
  2413. /*
  2414. if (res == SZ_OK && !Inline_MatchFinder_IsFinishedOK(&p->matchFinderBase))
  2415. res = SZ_ERROR_FAIL;
  2416. }
  2417. */
  2418. return res;
  2419. }
  2420. SRes LzmaEnc_Encode(CLzmaEncHandle pp, ISeqOutStream *outStream, ISeqInStream *inStream, ICompressProgress *progress,
  2421. ISzAllocPtr alloc, ISzAllocPtr allocBig)
  2422. {
  2423. RINOK(LzmaEnc_Prepare(pp, outStream, inStream, alloc, allocBig));
  2424. return LzmaEnc_Encode2((CLzmaEnc *)pp, progress);
  2425. }
  2426. SRes LzmaEnc_WriteProperties(CLzmaEncHandle pp, Byte *props, SizeT *size)
  2427. {
  2428. CLzmaEnc *p = (CLzmaEnc *)pp;
  2429. unsigned i;
  2430. UInt32 dictSize = p->dictSize;
  2431. if (*size < LZMA_PROPS_SIZE)
  2432. return SZ_ERROR_PARAM;
  2433. *size = LZMA_PROPS_SIZE;
  2434. props[0] = (Byte)((p->pb * 5 + p->lp) * 9 + p->lc);
  2435. if (dictSize >= ((UInt32)1 << 22))
  2436. {
  2437. UInt32 kDictMask = ((UInt32)1 << 20) - 1;
  2438. if (dictSize < (UInt32)0xFFFFFFFF - kDictMask)
  2439. dictSize = (dictSize + kDictMask) & ~kDictMask;
  2440. }
  2441. else for (i = 11; i <= 30; i++)
  2442. {
  2443. if (dictSize <= ((UInt32)2 << i)) { dictSize = (2 << i); break; }
  2444. if (dictSize <= ((UInt32)3 << i)) { dictSize = (3 << i); break; }
  2445. }
  2446. for (i = 0; i < 4; i++)
  2447. props[1 + i] = (Byte)(dictSize >> (8 * i));
  2448. return SZ_OK;
  2449. }
  2450. unsigned LzmaEnc_IsWriteEndMark(CLzmaEncHandle pp)
  2451. {
  2452. return ((CLzmaEnc *)pp)->writeEndMark;
  2453. }
  2454. SRes LzmaEnc_MemEncode(CLzmaEncHandle pp, Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen,
  2455. int writeEndMark, ICompressProgress *progress, ISzAllocPtr alloc, ISzAllocPtr allocBig)
  2456. {
  2457. SRes res;
  2458. CLzmaEnc *p = (CLzmaEnc *)pp;
  2459. CLzmaEnc_SeqOutStreamBuf outStream;
  2460. outStream.vt.Write = SeqOutStreamBuf_Write;
  2461. outStream.data = dest;
  2462. outStream.rem = *destLen;
  2463. outStream.overflow = False;
  2464. p->writeEndMark = writeEndMark;
  2465. p->rc.outStream = &outStream.vt;
  2466. res = LzmaEnc_MemPrepare(pp, src, srcLen, 0, alloc, allocBig);
  2467. if (res == SZ_OK)
  2468. {
  2469. res = LzmaEnc_Encode2(p, progress);
  2470. if (res == SZ_OK && p->nowPos64 != srcLen)
  2471. res = SZ_ERROR_FAIL;
  2472. }
  2473. *destLen -= outStream.rem;
  2474. if (outStream.overflow)
  2475. return SZ_ERROR_OUTPUT_EOF;
  2476. return res;
  2477. }
  2478. SRes LzmaEncode(Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen,
  2479. const CLzmaEncProps *props, Byte *propsEncoded, SizeT *propsSize, int writeEndMark,
  2480. ICompressProgress *progress, ISzAllocPtr alloc, ISzAllocPtr allocBig)
  2481. {
  2482. CLzmaEnc *p = (CLzmaEnc *)LzmaEnc_Create(alloc);
  2483. SRes res;
  2484. if (!p)
  2485. return SZ_ERROR_MEM;
  2486. res = LzmaEnc_SetProps(p, props);
  2487. if (res == SZ_OK)
  2488. {
  2489. res = LzmaEnc_WriteProperties(p, propsEncoded, propsSize);
  2490. if (res == SZ_OK)
  2491. res = LzmaEnc_MemEncode(p, dest, destLen, src, srcLen,
  2492. writeEndMark, progress, alloc, allocBig);
  2493. }
  2494. LzmaEnc_Destroy(p, alloc, allocBig);
  2495. return res;
  2496. }